@maiskiykot
Free coder

Как объединить в один запрос поиск в трех таблицах?

Приветствую. Понадобилось вести поиск (id, name) в трех таблицах. Стандартный запрос:
$participantsTable = Models::table('participants');
        $usersTable = Models::table('users');
        //$usersTable2 = Models::table('food_delivery_boy'); (эту таблицу хочу добавить)
        //$usersTable3 = Models::table('food_user'); (эту таблицу хочу добавить)
        $userPrimaryKey = Models::user()->getKeyName();
        $selectString = $this->createSelectString($columns);

        $participantNames = $this->getConnection()->table($usersTable)
            ->join($participantsTable, $usersTable . '.' . $userPrimaryKey, '=', $participantsTable . '.user_id')
            ->where($participantsTable . '.thread_id', $this->id)
            ->select($this->getConnection()->raw($selectString));
        if ($userId !== null) {
            $participantNames->where($usersTable . '.' . $userPrimaryKey, '!=', $userId);


Как правильно создать запрос?
  • Вопрос задан
  • 111 просмотров
Пригласить эксперта
Ответы на вопрос 1
alexey-m-ukolov
@alexey-m-ukolov Куратор тега Laravel
SELECT name FROM table1 where id = user_id
UNION ALL
SELECT name FROM table2 where id = user_id
UNION ALL
SELECT name FROM table3 where id = user_id


$first = DB::table('table1')
            ->where('id', 'user_id')
            ->select('name');

$second = DB::table('table2')
            ->where('id', 'user_id')
            ->select('name');

$third = DB::table('table3')
            ->where('id', 'user_id')
            ->select('name');

$results = $first
            ->union($second)
            ->union($third)
            ->get();
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы