bravik
bravik

Reputation: 460

Yii2 relational query help: select only records which have related records

I have two tables A and B with relationship "A has many B". A may not have any B records.

I need to write a query, which would select ONLY those A records, which have related records in Bs. Records which do not have related B-records should be ignored. Using Yii2 active record I'm also trying to load all A records with eager loading related B records. So here is what I have:

Movies::find()->with('shows')->all();

How do I add the neccesary condition to filter out movies without shows? How can I add any condition on movies which depends on shows data?

Upvotes: 1

Views: 964

Answers (1)

Fabrizio Caldarelli
Fabrizio Caldarelli

Reputation: 3008

Use innerJoinWith instead with, such as:

Movies::find()->innerJoinWith(['shows'])->all();

http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#innerJoinWith()-detail

Upvotes: 7

Related Questions