Laravel 5. Using the USING operator

Viewed 1179

I tried to find it for a long time, and I can't believe that Laravel doesn't have this functionality.

So, I can write:

select * from a join b where a.id = b.id

or more beautiful:

select * from a join b using(id)

First case is simple for Laravel:

$query->leftJoin('b', 'a.id', '=', 'b.id')

But how to write second case? I expect that it should be simple and short, like:

$query->joinUsing('b', 'id')

But thereis no such method and I can't find it.

PS: it's possible that the answer is very simple, it's just hard to find by word "using", because it's everywhere.

UPDATE

I'm going deeper to source, trying to make scope or pass a function to join, but even inside of this function I can't to anything with this $query. Example:

public function scopeJoinUsing($query, $table, $field) {
    sql($query->join(\DB::raw("USING(`{$field}`)")));
    // return 
    // inner join `b` on USING(`id`)  ``
    // yes, with "on" and with empty quotes
    sql($query->addSelect(\DB::raw("USING(`{$field}`)")));
    // return 
    // inner join `b` USING(`id`) 
    // but in fields place, before "FROM", which is very logic :)
}

So even if forget about scope , I can't do this in DB::raw() , so it's impossible... First time I see that something impossible in Laravel.

2 Answers

Nothing is impossible in Laravel.

Until support for join using is added to Laravel core, you can add support for it by installing this Laravel package: https://github.com/nihilsen/laravel-join-using.

It works like this:

use Illuminate\Support\Facades\DB;
use Nihilsen\LaravelJoinUsing\JoinUsingClause;

DB::table('users')->leftJoin(
    'clients',
    fn (JoinUsingClause $join) => $join->using('email', 'name')
);
// select * from `users` left join `clients` using (`email`, `name`)
Related