W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
belongsTo
,hasOne
,hasOneThrough
和 morphOne
關(guān)系允許你指定默認模型,當給定關(guān)系為 null
時,將會返回默認模型。 這種模式被稱作 空對象模式 ,可以減少你代碼中不必要的檢查。在下面的例子中,如果發(fā)布的帖子沒有找到作者, user
方法會返回一個空的 App\Models\User
模型:
/**
* 獲取帖子的作者
*/
public function user()
{
return $this->belongsTo('App\Models\User')->withDefault();
}
如果需要在默認模型里添加屬性, 你可以傳遞數(shù)組或者回調(diào)方法到 withDefault
中:
/**
* 獲取帖子的作者
*/
public function user()
{
return $this->belongsTo('App\Models\User')->withDefault([
'name' => 'Guest Author',
]);
}
/**
* 獲取帖子的作者
*/
public function user()
{
return $this->belongsTo('App\Models\User')->withDefault(function ($user, $post) {
$user->name = 'Guest Author';
});
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: