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...
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With