W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
在取得模型數(shù)據(jù)時,您可能想要以關(guān)聯(lián)模型作為查詢限制。例如,您可能想要取得所有「至少有一篇評論」的Blog 文章??梢允褂?has 方法達(dá)成目的:
$posts = Post::has('comments')->get();
也可以指定運(yùn)算符和數(shù)量:
$posts = Post::has('comments', '>=', 3)->get();
也可以使用"點(diǎn)號"的形式來獲取嵌套的 has 聲明:
$posts = Post::has('comments.votes')->get();
如果想要更進(jìn)階的用法,可以使用 whereHas 和 orWhereHas 方法,在 has 查詢里設(shè)置 "where" 條件 :
$posts = Post::whereHas('comments', function($q)
{
$q->where('content', 'like', 'foo%');
})->get();
Eloquent 可以經(jīng)由動態(tài)屬性取得關(guān)聯(lián)對象。 Eloquent 會自動進(jìn)行關(guān)聯(lián)查詢,而且會很聰明的知道應(yīng)該要使用 get(用在一對多關(guān)聯(lián))或是 first (用在一對一關(guān)聯(lián))方法。可以經(jīng)由和「關(guān)聯(lián)方法名稱相同」的動態(tài)屬性取得對象。例如,如下面的模型對象 $phone:
class Phone extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
}
$phone = Phone::find(1);
您可以不用像下面這樣打印用戶的 email :
echo $phone->user()->first()->email;
而可以簡寫如下:
echo $phone->user->email;
注意: 若取得的是許多關(guān)聯(lián)對象,會返回 Illuminate\Database\Eloquent\Collection 對象。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: