更新上層時(shí)間戳

2018-02-24 15:52 更新

當(dāng)模型 belongsTo 另一個(gè)模型時(shí),比方說(shuō)一個(gè) Comment 屬于一個(gè) Post ,如果能在子模型被更新時(shí),更新上層的時(shí)間戳,這將會(huì)很有用。例如,當(dāng) Comment 模型更新時(shí),您可能想要能夠同時(shí)自動(dòng)更新 Post 的 updated_at 時(shí)間戳。 Eloquent 讓事情變得很簡(jiǎn)單。只要在子關(guān)聯(lián)的類(lèi)里,把關(guān)聯(lián)方法名稱(chēng)加入 touches 屬性即可:

class Comment extends Model {
    protected $touches = ['post'];
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

現(xiàn)在,當(dāng)您更新 Comment 時(shí),對(duì)應(yīng)的 Post 會(huì)自動(dòng)更新 updated_at 字段:

$comment = Comment::find(1);
$comment->text = 'Edit to this comment!';
$comment->save();
以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)