Use the withCount function?
Model->with infinite loop problem
Hello, i have a database with multiple hasMany relations, like 'category' has many 'objects', 'objects' has many 'comments', etc. When i now get a list of objects, i want to include the category and the number of comments. (do this for all Models, so comments should include object and category should include object_count)
Include the category i can do with protected $with = array('category'); in my object model.
The comment_count i do like this: (original source: https://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/)
class Object extends Model
{
protected $with = array('commentsInfo');
protected $hidden = array('commentsInfo');
protected $appends = array('comment_count');
public function category()
{
return $this->belongsTo('App\Models\Category');
}
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
public function commentsInfo()
{
return $this->hasOne('App\Models\Comment')
->selectRaw('object_id, count(*) as comment_count')
->groupBy('object_id');
}
public function getCommentCountAttribute()
{
if (!$this->relationLoaded('commentsInfo')) {
$this->load('commentsInfo');
}
$related = $this->getRelation('commentsInfo');
return ($related) ? (int) $related->comment_count : 0;
}
}
Both works good, but together it ends in an infinite loop. So when Eloquent tries to count the comments, it loads the Comment Model which includes Objects again, but the Object again tries to load the comment_count, and so on. So far i understand what the Problem with this design is.
So is there a way to get the count relation as model property without loading the relations of the counted model?
Regards Moritz
Please or to participate in this conversation.