問題描述
假設(shè)我有一個像這樣的 Conversation
模型:
Suppose I have a Conversation
model like this :
class Conversation extends Model
{
public function questions (){
return $this->hasMany('AppQuestion','conversation_id','conversation_id');
}
public function category ()
{
return $this->belongsTo('AppCategory', 'cat', 'cat_id');
}
}
還有一個像這樣的 Question
模型:
And a Question
model like this:
class Question extends Model
{
public function conversation ()
{
return $this->belongsTo('AppConversation', 'conversation_id', 'conversation_id');
}
}
如您所見,這兩者之間存在 hasMany
關(guān)系.
As you can see there is a hasMany
relation between those two.
另一方面,有一個像下面這樣的 Category
與 Conversation
模型有關(guān)系:
In the other hand there is a Category
like below that has a relation with Conversation
model :
class Category extends Node
{
public function conversations (){
return $this->hasMany('AppConversation','cat','cat_id');
}
}
現(xiàn)在我想將一個名為 question_count
的屬性附加到 Category
來計算每個類別的對話的所有問題.為此,我添加了這個:
Now I want to append an attribute named question_count
to Category
that counts all questions of conversations of each category. for that I added this :
public function getQuestionsCountAttribute ()
{
return $this->conversations->questions->count();
}
但是在獲取類別時出現(xiàn)此錯誤:
But when fetch a category I got this error :
ErrorException in Category.php line 59:
Undefined property: IlluminateDatabaseEloquentCollection::$questions
我做了什么?如何在最小服務(wù)器過載的情況下計算關(guān)系的關(guān)系?
What did I do? how can I count relations of a relation with minimum server overloading?
我使用的是 Laravel 5.3.4.
I am using laravel 5.3.4.
推薦答案
我認(rèn)為這里你需要一個有很多的關(guān)系.
I think that you need a has many through relationship here.
你做錯了什么:
當(dāng)你寫$this->conversations->questions
時,這是行不通的,因為questions
是單個對話的關(guān)系 而不是對話的集合(這里,$this->conversations
是一個集合)
When you write $this->conversations->questions
, this can't work, because the questions
are a relation of a single conversation and not of a collection of conversations (here, $this->conversations
is a Collection)
解決辦法:
使用 hasManyThrough 關(guān)系:
Using hasManyThrough relation:
您可以在在此頁面上找到有關(guān)此關(guān)系的文檔,如果我的解釋不好
You can find the documentation for this relation on this page, if my explanation is bad
基礎(chǔ)是,你需要在你的 Category
模型上定義一個關(guān)系:
The basics are, you need to define a relation on your Category
model:
class Category extends Node
{
public function conversations ()
{
return $this->hasMany('AppConversation');
}
public function questions ()
{
return $this->hasManyThrough('AppQuestion', 'AppConversation');
}
}
(我會讓你查看非標(biāo)準(zhǔn)外鍵的文檔)
(I will let your look into the documentation for your non standards foreign keys)
然后你應(yīng)該可以使用:$category->questions->count()
這篇關(guān)于Laravel 中關(guān)系的計數(shù)關(guān)系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!