雄辩的-获取最新日期并将结果插入到另一个表中

梦想

我们有2张桌子

职称

+------+--------------------------------------+--------------+---------------------+
| id   | title                                | subs_updated | created_at          |
+------+--------------------------------------+--------------+---------------------+
|  104 | movie 1                              |              | 2014-11-11 12:08:28 |
|  129 | movie 2                              |              | 2014-11-11 12:08:29 |
+------+--------------------------------------+--------------+---------------------+

潜艇

+----+----------+----------+---------+---------------------+
| id |  label   | title_id | subs    | created_at          |
+----+----------+----------+---------+---------------------+
| 13 | English  |      104 | English | 2014-11-12 05:05:39 |
| 15 | Italian  |      104 | Italian | 2014-11-12 05:25:00 |
| 16 | Dutch    |      104 | Dutch   | 2014-11-13 05:40:51 |
| 18 | Arabic   |      129 | Arabic  | 2014-11-12 06:05:28 |
| 19 | Arabic   |      129 | Arabic  | 2014-11-12 06:07:23 |
+----+----------+----------+---------+---------------------+

在SubsController中,我有:

public function attach()
{
    $input = Input::except('_token');

    if ( ! Input::get('label') || ! Input::get('subs')) {
        return Response::json(trans('subs::main.fillAllRequiredFields'), 400);
    }

    if ( ! isset($input['title_id']))
    {
        return Response::json(trans('dash.somethingWrong'), 500);
    }

    else
    {
        $this->model->fill($input)->save();
    }

    return Response::json($this->model, 201);
}


潜艇模型

<?php

class Link extends Entity {

    public $table = 'subs';

    protected $guarded = array('id');

    public function title()
    {
        return $this->belongsTo('Title');
    }
}
  1. 我想按创建日期(created_at)在subs表中查找标题(title_id)的最新子。
  2. 将结果(日期)插入标题表=>标题(id)=> subs_updated
  3. 将该查询与上面的attach()函数一起使用


任何帮助都非常感谢

Lukasgeiter

如果我正确分析了您的问题,则您希望在subs_updated每次创建新的子项时进行更新使用模型事件可以很好地做到这一点

Sub模型中,重写boot()以注册事件:

public static function boot(){
    parent::boot();

    self::created(function($sub){
        $title = $sub->title;
        if( ! is_null($title)){
            $title->subs_updated = $sub->created_at;
            $title->save();
        }
    });
}

如果您想在subs_updated每次更新或创建子项时进行更新,则可以使用该saved事件:

self::saved(function($sub){ ...

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章