M
M
maiskiykot2021-11-16 09:56:37
Laravel
maiskiykot, 2021-11-16 09:56:37

How to combine searches in three tables into one query?

Greetings. It was required to search (id, name) in three tables. Standard request:

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


How to create a request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-11-16
@alexey-m-ukolov

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question