0

I have defined a relation in Yii2 in which every website can have multiple feeds:

public function getFeeds() {
    return $this->hasMany(Feed::className(), ['website_id' => 'id']);
}

Now consider following query:

$ids = [2, 3];
$feeds = Website::find()->where(['user_id' => 1])->with(['feeds' => function($query) use ($ids) {
    $query->where(['id' => $ids);
}])->all();

The corresponding raw SQL queries are:

SELECT * FROM `website` WHERE `user_id`= 1 // returns 4, 5, 6
SELECT * FROM `feed` WHERE (`id` IN (2, 3)) AND (`website_id` IN (4, 5, 6))

My questions is, can I have delete version of this query using Active Record? Something like this:

SELECT * FROM `website` WHERE `user_id`= 1
DELETE FROM `feed` WHERE (`id` IN (2, 3)) AND (`website_id` IN (4, 5, 6))

Any help would be appreciated.

2 Answers 2

1

You may do as this:

$query = Website::find()
    ->select('id')
    ->where(['user_id' => 1]);

Feed::deleteAll([
    'id' => [2, 3],
    'website_id' => $query
]);
Sign up to request clarification or add additional context in comments.

Comments

0

In this case could be better a CreateCommand

for do this you should bild raw query using join eg:

select * 
from `feed` 
join `website` on `website`.id = `feed`.`website_id`
WHERE website`.`user_id`= 1
AND  `feed`.id  IN (2, 3) 

or for delete

delete 
from `feed` 
join `website` on `website`.id = `feed`.`website_id`
WHERE website`.`user_id`= 1
AND  `feed`.id  IN (2, 3) 

then for Yii2

$sql = "delete 
        from `feed` 
        join `website` on `website`.id = `feed`.`website_id`
        WHERE website`.`user_id`= 1
        AND  `feed`.id  IN (2, 3);"

Yii::$app->db->createCommand($sql)->execute();

1 Comment

Thanks, but I want to create this query using Active Record, just like the select version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.