Laravel query contains `where exists ( select ....)`

45 views Asked by At

I have an many to many and try to query data by two conditions. The first verify the station_code in table station and the second is a like condition in on column name in table Products

$stationListWithProducts = Station::with('products')
  ->where('station_code', '=', $stationCode)
  ->whereRelation('products', 'name', 'like', '%Price%');

If i execute toRawSql() the query is

select * from `stations` where `station_code` = 'device-A' and exists 
(select * from ... where ... and `name` like '%Price%') 

What's confusing me is, that and existis in the query. I've expect that the whereRelation add a join and add the condition to my query, not an exists condition, which contains a the condition.

How can create the query with a condition on both tables, an what is wrong of my point of view?

1

There are 1 answers

1
michael-mammut On

Ok, I've found my problem. I've just requested the Station model. Now it's clear to me. After add the where condition, i've to keep on working on the relation and fetch the data from there.

Now the query is correct, an the data too. :)

Station::firstWhere('station_code', '=', $stationCode)
            ->products()
            ->where('name', 'like', "%$filterValue%")
            ->get();