假设我有一个像这样的 Conversation
模型:
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
关系 .
另一方面,下面的 Category
与 Conversation
模型有关系:
class Category extends Node
{
public function conversations (){
return $this->hasMany('App\Conversation','cat','cat_id');
}
}
现在我想将一个名为 question_count
的属性追加到 Category
,它会计算每个类别对话的所有问题 . 为此我添加了这个:
public function getQuestionsCountAttribute ()
{
return $this->conversations->questions->count();
}
但是当获取类别时我得到了这个错误:
ErrorException in Category.php line 59:
Undefined property: Illuminate\Database\Eloquent\Collection::$questions
我做了什么?如何计算关系与最小服务器重载的关系?
我正在使用laravel 5.3.4 .
3 回答
我认为你需要一个有很多关系的人 .
What you do wrong:
当您编写
$this->conversations->questions
时,这不起作用,因为questions
是 a single conversation 的关系而不是对话集合(此处,$this->conversations
是集合)The solution:
使用hasManyThrough关系:
如果我的解释不好,您可以找到此关系的文档on this page
基础知识是,您需要在
Category
模型上定义关系:(我会让你看看你的非标准外键的文档)
You should then be able to use: $category->questions->count()
$this->conversations 包含会话集合 . 每个会话都有自己的 questions 属性,其中包含该对话的所有相关问题,但集合本身没有 questions 属性,其中包含该类别的所有相关问题 .
为了能够计算该类别中所有问题的计数,您需要定义一个将问题直接链接到该类别的 hasManyThrough 关系 .
首先,将关系添加到 Category 模型:
一旦你拥有它,你将能够得到一个类别的所有问题的计数:
您可以使用'withCount'方法计算相关模型 . https://laravel.com/docs/5.3/eloquent-relationships#counting-related-models