在laravel中计算关系的关系 [英] count relation of relation in laravel
问题描述
假设我有一个像这样的Conversation
模型:
Suppose I have a Conversation
model like this :
class Conversation extends Model
{
public function questions (){
return $this->hasMany('App\Question','conversation_id','conversation_id');
}
public function category ()
{
return $this->belongsTo('App\Category', 'cat', 'cat_id');
}
}
和这样的Question
模型:
class Question extends Model
{
public function conversation ()
{
return $this->belongsTo('App\Conversation', 'conversation_id', 'conversation_id');
}
}
如您所见,这两者之间存在一个hasMany
关系.
As you can see there is a hasMany
relation between those two.
另一方面,如下所示的Category
与Conversation
模型有关:
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('App\Conversation','cat','cat_id');
}
}
现在,我想向Category
附加一个名为question_count
的属性,该属性计算每个类别的对话的所有问题.为此,我添加了这个:
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();
}
但是在获取类别时,出现此错误:
But when fetch a category I got this error :
ErrorException in Category.php line 59:
Undefined property: Illuminate\Database\Eloquent\Collection::$questions
我做了什么?如何计算具有最小服务器超载的关系的关系?
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.
推荐答案
我认为您需要在这里拥有很多直通关系.
I think that you need a has many through relationship here.
您在做什么:
编写$this->conversations->questions
时,此操作不起作用,因为questions
是单个对话的关系,而不是对话集合的关系(此处,$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关系:
Using hasManyThrough relation:
您可以在此页面上上找到该文档,如果我的解释不好
You can find the documentation for this relation on this page, if my explanation is bad
基础是,您需要在Category
模型上定义一个关系:
The basics are, you need to define a relation on your Category
model:
class Category extends Node
{
public function conversations ()
{
return $this->hasMany('App\Conversation');
}
public function questions ()
{
return $this->hasManyThrough('App\Question', 'App\Conversation');
}
}
(我会让您查看非标准外键的文档)
(I will let your look into the documentation for your non standards foreign keys)
然后您应该可以使用:$category->questions->count()
You should then be able to use: $category->questions->count()
这篇关于在laravel中计算关系的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!