Yii2使用关系删除查询

时间:2016-11-09 21:41:28

标签: php yii yii2

我在Yii2中定义了一个关系,其中每个网站都可以有多个Feed:

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

现在考虑以下查询:

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

相应的原始SQL查询是:

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))

我的问题是,我可以使用Active Record删除此查询的版本吗?像这样:

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

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以这样做:

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

Feed::deleteAll([
    'id' => [2, 3],
    'website_id' => $query
]);

答案 1 :(得分:0)

在这种情况下,CreateCommand

可能更好

要执行此操作,您应该使用连接bild原始查询,例如:

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

或删除

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

然后是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();