简体   繁体   中英

How to join same table multiple times in Laravel?

I have tables users, user_traits and traits. What I'm wondering is what is the simplest and most efficient way to show a list of users sorted in some way with first 5 traits.(I am using Laravel 8 and SQL)

users: (id, name, .... ) user_traits: (id, user_id, trait_id, trait_order, trait_importance, ...) traits: (id, trait_name, trait_value, ....)

the result I'm looking for is something like: (id, name, trait_name1, trait_value1, trait_name2, trait_value2, trait_name3, trait_value3, trait_name4, trait_value4, trait_name5, trait_value5);

current code:

$users = DB::table('users')->where(...)
            ->leftJoin('user_traits as trait1', function($join){
                    $join->on('trait1.user_id', '=', 'users.id')
                        ->where('trait1.trait_order', 1);
                }
            )
            ->leftJoin('user_traits as trait2', function($join){
                    $join->on('trait2.user_id', '=', 'users.id')
                        ->where('trait1.trait_order', 2);
                }
            ).... up to 5
            ->leftJoin('traits as actualtrait1', function($join){
                $join->on('actualtrait1.id', '=', 'trait1.trait_id');
                }
            )
            ->leftJoin('traits as actualtrait2', function($join){
                $join->on('actualtrait2.id', '=', 'trait2.trait_id');
                }
            )....up to 5

Any help would be welcome and thank you in advance.

you can use laravel relation and eager loading

in user model add

public function traits()
{
  return $this->belongToMany(Trait::Class,'user_traits');
}

this will return all traits associated with the user

then you could do something like that

$users = User::with(['traits' => function($query) {
    $query->take(5);
}])->get();

For example you want to use color table two time in join you can use like this first time table name change color as xc and second time color as ic

DB::table('vehicles')
->join('colors as xc', 'vehicles.color', '=', 'xc.id')
->join('colors as ic', 'vehicles.interior_color', '=', 'ic.id')
->select('vehicles.*', 'xc.name as xcolor','ic.name as icolor')
->where('vehicles.id',$id)
->first();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM