How to check that a hasMany relation entry is empty in eloquent laravel
I need that those records that have no participation have many tables my query like this
$result = Recipes::select('id')->where("name", 'like', '%' . $item . '%')
->with(['categoryItem'])
->get();
And my conclusion
Array
(
[0] => Array
(
[id] => 1
[category_item] => Array
(
[0] => Array
(
[id] => 2
[foodable_id] => 1
[foodable_type] => Recipes
[created_at] => 2017-04-14 16:18:22
)
)
)
[1] => Array
(
[id] => 4
[category_item] => Array
(
)
)
)
I only want to retrieve posts that have an empty category_item detail. in the following example i want to get the index 1 of the record, as i can give a condition with a query
source to share
If you understood correctly and want to get recipes that don't have categoryItem
, you want to use the doesntHave()
method:
Recipes::where('name', 'like', '%'.$item.'%')
->doesntHave('categoryItem')
->get();
I am assuming the categoryItem
relationship is defined as you are trying to use it in a method with()
.
source to share
Hello, Maybe this can help. Don't forget to add on top of your file:
use DB;
And your result will be something like this
$result = Recipes::select('id')->where("name", 'like', '%' . $item . '%')
->whereHas('categoryItem', function($q) {
$q->where(DB::raw('count(*)),'>', 0);
})->get();
I haven't tested the counting function, hope it works, Good luck with it
source to share