A
A
akdes2017-07-28 12:49:52
Laravel
akdes, 2017-07-28 12:49:52

How to get a model that has a model that has foo like bar?

Hello.
Need to find a device that has an attribute that has foo like "bar"
Example in SQL:
device n:m attribute

select device.id from device where device.id in 
   (select device_id from device_attribute where attribute_id in  
      (select attribute.id from attribute where attribute.foo like "bar")
   )

Tell me how to do it the smart way? I could look for attribute first, and then get device.
$attr = Attribute::where('foo', 'like', 'bar')->first();
$device = $attr->device()->first();

But it reverses the logic.
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
imhuman, 2017-07-28
@akdes

$devices = Device::whereHas('attributes', function ($query) {
    $query->where('foo', 'like', 'bar');
})->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question