我知道,你可以自動檢索通過把關係中的一個模型類以下內容:自動獲得「withCount」
protected $with = [
'users', 'scores'
];
但有可能做同樣與「withCount」?
我試過,但沒有奏效:
protected $withCount = [
'users'
];
我知道,你可以自動檢索通過把關係中的一個模型類以下內容:自動獲得「withCount」
protected $with = [
'users', 'scores'
];
但有可能做同樣與「withCount」?
我試過,但沒有奏效:
protected $withCount = [
'users'
];
如果你想擁有包括在陣列形式輸出相關模型的計數,你必須先創建一個accessor並把它在模型的$appends
數組中。
定義訪問
// In your model
public function getUserCountAttribute() {
$users = $this->users; // From the relationship you defined
return $users->count();
}
您現在可以在你的對象使用userCount
屬性。
的userCount
屬性添加到$appends
陣列中的模型類
// In your model
protected $appends = ['userCount'];
對於'$ this-> users() - > count()'而不是'$ this-> users-> count()'會更好,因爲第一個在一個查詢中完成所有操作,但是第二個加載每個相關用戶然後統計它們。 – ntzm
這是不正確的。假設您已經加載了該對象的相應關係**,則通過方法' - > users()'或屬性' - > users'調用相關模型都會返回相關對象的'Collection'。 ' - > count()'方法是由'Collection'類提供的,所以調用' - > count()'不會查詢數據庫,而只是計算'Collection'中的項數。它們唯一的區別是,如果你還沒有加載關係,' - > users'將會返回'null',但' - > users()'會立即從數據庫中查詢相關的對象。 –
看看[這裏](https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Relations/Relation.php)。這是一種關係方法返回的結果。你可以看到它擁有一個查詢,所有在' - > users()上調用的方法將作爲查詢運行,而不是集合。 – ntzm
顯然,沒有這樣的事情。 – linuxartisan