Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent get relation count

Tags:

php

laravel

I use Laravel 5.3.

I have 2 tables :

Articles --------- id cat_id title 

And

Category --------- id parent_id title 

I have defined my relations in my models :

// Article model public function category() {     return $this->belongsTo(Category::class); }  // Category model public function children()  {     return $this->hasMany(Category::class, 'parent_id', 'id'); }    

Is there an easy way using Eloquent to have a list a categories with count of articles. The difficulty is that I want to group categories where id_parent = 0, i.e. I want to display only parent categories with count of articles in children.

I tried something like that :

    $category = new \App\Models\Category();     $categoryTable = $category->getTable();      return $category->leftJoin('article', 'article.cat_id', '=', 'category.id')         ->whereIn('article.cat_id', function($query)             {                 $query->select('cat_id')                     ->from('categories')                     ->where('categories.parent_id', ???)                     ->orWhere($this->tableName .'.cat_id', $id);             })         ->groupBy('cat_id'); 

But I am lost...

like image 583
Vincent Decaux Avatar asked Dec 15 '16 13:12

Vincent Decaux


People also ask

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.


1 Answers

you can use withCount(). It is available from 5.3 version

for more info about eloquent visit : https://laravel.com/docs/5.3/eloquent-relationships

like image 154
kapil.dev Avatar answered Oct 09 '22 23:10

kapil.dev