Skip to content
Advertisement

Laravel Query Builder joining with alias

I have two tables

Unknown table

id | parent_id 

Clients table

id | parent_id  

My Code :

$transaction = DB::table($name.'_transactions')
                    ->where('user_id', $id)
                    ->join('users', 'users.id' , '=' , 'parent_id')
                    ->get();

Joining will be with the clients.id => unknown.parent_id… As because the clients table has a parent_id that’s why i have to use the alias

Please Help me to do so!

Advertisement

Answer

Using Alias Working Solution:

$tablename = Roles::where('id', '=' , 6)->first();
                    $name = str_replace(' ', '_', trim($tablename->name));
                    $tb = $name.'_transactions';
                    $exist_in_db = DB::table($tb)
                                        ->where('user_id', $id)
                                        ->get();
                    if(count($exist_in_db) > 0) {
                        $transaction = DB::table("$tb as newtable")
                                        ->where('user_id', $id)
                                        ->join('users', 'users.id' , '=' , 'newtable.parent_id')
                                        ->get();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement