E
E
Eugene2022-03-24 09:26:33
Laravel
Eugene, 2022-03-24 09:26:33

How to set a condition for a linked table when fetching data?

A little confused. It seems like a simple question in my head, but I can not find a solution.

How to set a condition when selecting with Eloquent, which would be checked for the presence of data in the associated table. Those. I need the row to get only if it has data in the associated table.

There is withCount('myProp') which gives the number of records in the related table, but what is the right way to use it in the where condition (withCount('myProp') > 0)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pLavrenov, 2022-03-24
@atachrus

There is also has()
$users = User::has('posts')->get();
or

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question