Laravel 5.3 Withcount() Nested Relation

Laravel 5.3 withCount() nested relation

You can only do a withCount() on a defined relation of the model.

However, a relationship can be hasManyThrough which would achieve what you are after.

class Tutorial extends Model
{
function chapters()
{
return $this->hasMany('App\Chapter');
}

function videos()
{
return $this->hasManyThrough('App\Video', 'App\Chapter');
}
}

And then you can do:

Tutorial::withCount(['chapters', 'videos'])

Docs:

  • https://laravel.com/docs/5.3/eloquent-relationships#has-many-through

How to do nested eloquent relation

You can simply do it by the following line:

A::with('B.C')->get()

Then every A-object will have their associated B models, and every B-model will have their C-objects included.

Load laravel eloquent model withCount of related model

Try this:

public function customer() {
return $this->belongsTo(Customer::class)->withCount('bookings');
}

Booking::whereNotCancelled()->with('customer')->get();

Use withCount method with some condition

If you only want the music models that have a positive rate:

Music::whereHas('rates', function ($q) {
$q->where('rate_type', true);
})
->where('created_at', '>=', Carbon::parse('last saturday'))
->withCount('rates')
->orderby('rates_count', 'desc')
->get();

If you want all music models but only load the positive rates:

Music::with([
'rates' => function ($q) {
$q->where('rate_type', true);
}
])
->where('created_at', '>=', Carbon::parse('last saturday'))
->withCount('rates')
->orderby('rates_count', 'desc')
->get();

Use DISTINCT in Laravel's withCount() method

User::withCount('views', function($query) {
$query->select(DB::raw('count(distinct(ip))'));
})->get();

Count relations that have a relation in Laravel

you can try has

Category Model

class Category extends Model
{
public function questions()
{
return $this->hasMany(Question::class);
}

function answers()
{
return $this->hasManyThrough(Answer::class, Question::class);
}
}

Fetch data

$categories = Category::withCount('questions')->has('answers')->get();

foreach($categories as $category){
$category->name." - ". $category->questions_count;
}

Here questions_count is total question that has at least one answer for that category

Laravel5 ORM : how to alias multiple withCount on the same related object

Instead of specifying where clause in your withCount define the relation for occupied rooms in Hotel Model.

public function occupied_rooms(){
return $this->hasMany(Room::class)
->where('status', 'Occupied');
}

Now, in your controller use, withCount('occupied_rooms').

$hotels = Hotel::where('foo',$bar)
->withCount(['rooms','occupied_rooms'])
->get();


Related Topics



Leave a reply



Submit