Yii2. Как добавить в WHERE IN кастомный QUERY запрос

Рейтинг: 0Ответов: 1Опубликовано: 12.01.2023

У меня есть такой запрос WHERE.

where
  (posts.id in (
    select posts.id from posts
    where posts.carId in (
      select car_subscription.carId from car_subscription
      where car_subscription.userId = 37
    )
  )
  or
    posts.id in (
    select posts.id from posts
    where posts.userId in (
      select user_subscription.userSubId from user_subscription
      where user_subscription.userId = 37
    )
  ) )

Как построить такой запрос с помощью yii2?. Как в where in вставить SELECT

    $query->where(['in', 'posts.id', ''])
            ->orWhere(['in', 'posts.id', '']);

Ответы

▲ 0

В Yii2 можете использовать Query Builder для создания SQL-запроса с подобной структурой. Вот пример построения конструктора в Yii2:

$subquery1 = (new Query())
->select(['posts.id'])
->from('posts')
->where(['in', 'posts.carId', (new Query())
    ->select(['car_subscription.carId'])
    ->from('car_subscription')
    ->where(['car_subscription.userId' => 37])
]);

$subquery2 = (new Query())
    ->select(['posts.id'])
    ->from('posts')
    ->where(['in', 'posts.userId', (new Query())
        ->select(['user_subscription.userSubId'])
        ->from('user_subscription')
        ->where(['user_subscription.userId' => 37])
    ]);

$query = (new Query())
    ->select(['*'])
    ->from('posts')
    ->where(['or', ['in', 'posts.id', $subquery1], ['in', 'posts.id', $subquery2]]);

$results = $query->all();