Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

johnw65's avatar

Query Builder: How to return 2 results from one query

I'm relatively new to Laravel and this is probably a basic question

I have a following query using Query Builder and would like to send two query responses. If I can, I don't want to create another query.

First one with -distinct('firstTable.firstTable_seq'), and the other one without. How can I accomplish this. Thank you in advance.


 $search = DB::table('firstTable')


select('firstTable.firstTable_seq as unique_no', 'firstTable.*', 'firstTable.visit_from_date', 'firstTable.case_id')


->leftJoin('2ndTable', 'firstTable.id', '=', '2ndTable.id')



                     //create another query without distinct
                     ->distinct('firstTable.firstTable_seq')

                   
            
                    ->get();

                    ndQuery="without distinct";

                 return response()->json(array('result' => $search, '2ndQuery'=>ndQuery));
0 likes
6 replies
Tray2's avatar

Distinct should be avoided if possible.

However what do you mean by two query responses?

Are the tables related like author and book or is it more like authors and artists and you want to list both the artists and the authors with one query?

johnw65's avatar

Tray2,

Understand that distinct should be avoided, but in this case, I need to use distinct to display all of the main records and use the 2nd query to display the join from two tables. Thanks!

Tray2's avatar

so something like this then?

SELECT * FROM table1
UNION ALL
SELECT * FROM table2
johnw65's avatar

Walihn:

I need to clarify my question.

  1. I'm running a search criteria which has a join on table1 (author) and table 2(books).
  2. So currently , I'm running two separate queries.
  3. The main difference is that in one query, i'm adding ->distinct('table1.firstTable_seq')
  4. so query #1 returns all of authors
  5. query #2 returns author/books.

So to optimize performance, can I return 2 results by running one query.

Apologize for the confusion. Thanks.

Tray2's avatar
Tray2
Best Answer
Level 73

Are you trying to use the same query to do two different things?

  1. Index fetch all authors (With pagination of course)
  2. Show fetch one author and all the books by that author

Or are you trying to do something like

Author1
   - book1
   - book2
Author2
  - book3
  - book4
Author3
 - book5

In that case you shoud do something like

$authors = Author::with('books')->get();

That will get you each author and all the books belonging to that author.

=> Illuminate\Database\Eloquent\Collection {#1983
     all: [
       App\Models\Author {#1990
         id: 1,
         first_name: "Robert",
         last_name: "Jordan",
         slug: "jordan-robert",
         created_at: "2020-12-05 10:56:20",
         updated_at: "2020-12-05 10:56:20",
         books: Illuminate\Database\Eloquent\Collection {#2004
           all: [
             App\Models\Book {#2010
               id: 1,
               title: "The Eye Of The World",
               series: "The Wheel Of Time",
               part: 1,
               format_id: 1,
               genre_id: 1,
               isbn: "9780812511819",
               released: 1990,
               reprinted: 1990,
               pages: 814,
               blurb: "The Wheel of Time turns and Ages come and go, leaving memories that become legend. Legend fades to myth, and even myth is long forgotten when the Age that gave it birth returns again. In the Third Age, an Age of Prophecy, the World and Time themselves hang in the balance. What was, what will be, and what is, may yet fall under the Shadow.",
               created_at: "2020-12-05 10:56:20",
               updated_at: "2020-12-05 10:56:20",
               pivot: Illuminate\Database\Eloquent\Relations\Pivot {#2007
                 author_id: 1,
                 book_id: 1,
               },
             },
             App\Models\Book {#2011
               id: 2,
               title: "The Great Hunt",
               series: "The Wheel Of Time",
               part: 2,
               format_id: 1,
               genre_id: 1,
               isbn: "9780812517729",
               released: 1990,
               reprinted: 1991,
               pages: 70,
               blurb: "The Wheel of Time turns and Ages come and pass. What was, what will be, and what is, may yet fall under the Shadow. Let the Dragon ride again on the winds of time.",
               created_at: "2020-12-05 10:56:20",
               updated_at: "2020-12-05 10:56:20",
               pivot: Illuminate\Database\Eloquent\Relations\Pivot {#2009
                 author_id: 1,
                 book_id: 2,
               },
             },
             App\Models\Book {#2012
               id: 3,
               title: "A Memory Of Light",
               series: "The Wheel Of Time",
               part: 14,
               format_id: 2,
               genre_id: 1,
               isbn: "9780765325952",
               released: 2013,
               reprinted: null,
               pages: 700,
               blurb: "The Wheel of Time turns and Ages come and go, leaving memories that become legend. Legend fades to myth, and even myth is long forgotten when the Age that gave it birth returns again. In the Third Age, an Age of Prophecy, the World and Time themselves hang in the balance. What was, what will be, and what is, may yet fall under the Shadow.",
               created_at: "2020-12-05 10:56:20",
               updated_at: "2020-12-05 10:56:20",
               pivot: Illuminate\Database\Eloquent\Relations\Pivot {#2003
                 author_id: 1,
                 book_id: 3,
               },
             },
           ],
         },
       },
       App\Models\Author {#1996
         id: 7,
         first_name: "Brandon",
         last_name: "Sanderson",
         slug: "sanderson-brandon",
         created_at: "2020-12-05 10:56:20",
         updated_at: "2020-12-05 10:56:20",
         books: Illuminate\Database\Eloquent\Collection {#1989
           all: [
             App\Models\Book {#2013
               id: 3,
               title: "A Memory Of Light",
               series: "The Wheel Of Time",
               part: 14,
               format_id: 2,
               genre_id: 1,
               isbn: "9780765325952",
               released: 2013,
               reprinted: null,
               pages: 700,
               blurb: "The Wheel of Time turns and Ages come and go, leaving memories that become legend. Legend fades to myth, and even myth is long forgotten when the Age that gave it birth returns again. In the Third Age, an Age of Prophecy, the World and Time themselves hang in the balance. What was, what will be, and what is, may yet fall under the Shadow.",
               created_at: "2020-12-05 10:56:20",
               updated_at: "2020-12-05 10:56:20",
               pivot: Illuminate\Database\Eloquent\Relations\Pivot {#2000
                 author_id: 7,
                 book_id: 3,
               },
             },
           ],
         },
       },
       App\Models\Author {#1997
         id: 8,
         first_name: "David",
         last_name: "Eddings",
         slug: "eddings-david",
         created_at: "2020-12-05 10:56:20",
         updated_at: "2020-12-05 10:56:20",
         books: Illuminate\Database\Eloquent\Collection {#1998
           all: [
             App\Models\Book {#2014
               id: 4,
               title: "Pawn Of Prophecy",
               series: "The Balgariad",
               part: 1,
               format_id: 1,
               genre_id: 1,
               isbn: "9780345468642",
               released: 1982,
               reprinted: 2004,
               pages: 304,
               blurb: "A magnificent epic set against a history of seven thousand years of the struggles of Gods and Kings and men - of strange lands and events - of fate and a prophecy that must be fulfilled! THE BELGARIAD Long ago, so the Storyteller claimed, the evil God Torak sought dominion and drove men and Gods to war. But Belgarath the Sorcerer led men to reclaim the Orb that protected men of the West. So long as it lay at Riva, the prophecy went, men would be safe. But that was only a story, and Garion did not believe in magic dooms, even though the dark man without a shadow had haunted him for years. Brought up on a quiet farm by his Aunt Pol, how could he know that the Apostate planned to wake dread Torak, or that he would be led on a quest of unparalleled magic and danger by those he loved - but did not know? For a while his dreams of innocence were safe, untroubled by knowledge of his strange heritage. For a little while... THUS BEGINS BOOK ONE OF THE BELGARIAD",
               created_at: "2020-12-05 10:56:20",
               updated_at: "2020-12-05 10:56:20",
               pivot: Illuminate\Database\Eloquent\Relations\Pivot {#2001
                 author_id: 8,
                 book_id: 4,
               },
             },
           ],
         },
       },
     ],
   }

Please or to participate in this conversation.