Laravel 5 (Eloquent) JOIN between two consultations, is it possible?

Asked

Viewed 721 times

0

The following SQL, executes two queries and "sums" the hard answers "laterally":

 select * from (select id,name from client  where id = 20) as a

 join  (select id,age from client  where id = 20) as b

 ON a.id = b.id

I wonder if it is possible to do this using eloquent, without using pure SQL (DB::Raw()). The two isolated consultations would look like this:

 $query1 = DB::table('client')->select('id','nome')->where('id','=',20);
 $query2 = DB::table('client')->select('id','age')->where('id','=',20);

Now, how to do:

 $query1->join($query2)...:

Before you tell me the obvious "it’s possible to have the same answer in a single query," that’s just one example, in the real context, believe it is not possible to bring all information at once.

  • Well, I gave the answer, but I still think you want it’s a little different. wherein in your case would solve?

  • http://stackoverflow.com/questions/16848987/a-join-with-additional-condition-using-query-builder-or-eloquent

  • Merge conditions do not resolve in my case, because I can’t pass a query object as the first parameter in JOIN... I’m almost convinced that what I want to do is impossible, now I’m among, join the results via PHP. Or write all the code inside a DB::Raw(). The second option is bad, because I wanted my system to be completely portable, with respect to the database, but if I put syntax of a specific DBMS, it will go down :(

  • Does the method $query->toSql() can’t help you?

  • This method exists, apparently not? if I can get the query that eloquent generated, and do JOIN on the arm, it would be a much better solution. But at other times I needed to access the generated SQL (debug), and the only means I found was used "queryLog", which obtains the query, but only after it is executed.

  • This wouldn’t be a union or union all? More information here: https://laravel.com/docs/5.7/queries#Unions

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.