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');
}
}
And a Question
model like this:
class Question extends Model
{
public function conversation ()
{
return $this->belongsTo('App\Conversation', 'conversation_id', 'conversation_id');
}
}
As you can see there is a hasMany
relation between those two.
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');
}
}
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?
I am using laravel 5.3.4.