Eloquent: how to where count relation ship ? In my model TeamleaderDeal :
public function tasks()
{
return $this->hasMany('App\Task');
}
controller:
(...)
$deals = TeamleaderDeal::orderBy($this->sorting, $this->sortOrder);
(...)
$deals->whereHas(
'tasks',
function ($query) use ($condition) {
dd($query);
}
How to make this condition? : where count of the relation ship tasks equal to 5
thanks
With Laravel, you can count the number of results from a relationship without actually loading them:
Use withCount('tasks'):
$deals = TeamleaderDeal::withCount('tasks') . . .
Now in your deal model, you will have a tasks_count column.
$dealsWithFiveTasks = $deals->where('tasks_count', 5)->all();
@Amaury
Thank you.
I tested it:
(Attendance::select('id')->withCount('services')->latest()->limit(100)->get())
->where('services_count', '>=', 3);
@amaury Thanks , `
It says that column doesn't exists :
SQLSTATE[42703]: Undefined column: 7 ERROR: column "tasks_count" does not exist LINE 1
the where('tasks_count', 5) must be applied to the collection, not when querying the database.
First query the database:
$deals = TeamleaderDeal::withCount('tasks')->get();
Then on the collection:
$dealsWithFiveTasks = $deals->where('tasks_count', 5)->all();
@x what do you mean? where statements ALWAYS apply when querying the database
what are you trying to achieve?
@snapey
I have two models : TeamleaderDeal and Task .
the relationship is :
TeamleaderDeal model:
public function tasks()
{
return $this->hasMany('App\Task');
}
public function getTasksCountAttribute()
{
return $this->hasMany('App\Task')->count();
}
Task model:
public function teamleaderDeal()
{
return $this->belongsTo(TeamleaderDeal::class);
}
I want to make a condition to show only teamleaderDeals having more than X number of tasks :
$deals = TeamleaderDeal::orderBy($this->sorting, $this->sortOrder);
return (
//
//I want to return only deals with X number of tasks !
//
)
@GodziLaravel
$query()->whereHas('tasks', operator: '>', count: $count);
will produce the following SQL
select *
from "teamleader_deals"
where (select count(*)
from "tasks"
where "teamleader_deals"."id" = "tasks"."teamleader_deal_id") < ?
just use
$query->has('tasks','=',X);
Use having:
$model
->withCount('members')
->having('members_count', '>', 0)
->get();
This worked perfectly! Thank you 🙌
@digitaloutback This keeps returning 'SQLSTATE[42703]: Undefined column: 7 ERROR: column "transactions_count" does not exist for me
@seewhy try making a new thread with your own exact code
Please sign in or create an account to participate in this conversation.