關(guān)聯(lián)查詢

2018-02-24 15:52 更新

根據(jù)關(guān)聯(lián)條件查詢

在取得模型數(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();

動態(tài)屬性

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 對象。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號