W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
當(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();
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: