User::with('dealer', 'role')->get()
Is there a better way to make this query?
Hello All,
I have a query that works as it is, but I'm thinking there could possibly be a better and more efficient way to run it. It suits it's purpose the way it is.
Please review and let me know if you think there is a way that is better.
Models:
// Dealer
public function users()
{
return $this->hasMany('Dbn\User');
}
// User
public function dealer()
{
return $this->belongsTo('Dbn\Dealer');
}
public function role()
{
return $this->belongsToMany('Dbn\Role');
}
// Role
public function users()
{
return $this->belongsToMany('Dbn\User');
}
// role_user - pivot table
user_id
role_id
// Tables:
dealers
users
roles
role_user
// DB query
Datatables::of(DB::table('users'))
->leftJoin('dealers', 'dealers.id', '=', 'users.dealer_id')
->leftJoin('role_user', 'role_user.user_id', '=', 'users.id')
->leftJoin('roles', 'roles.id', '=', 'role_user.role_id')
->select(DB::raw('role_user.role_id,roles.display_name,
dealers.name,users.id,users.prefix,users.first_name,users.last_name,
users.suffix,users.email,users.created_at'))
->where('users.deleted_at', null)
->make(true);
Not all users are related to a dealer. I tried join but will only return those that have a dealer_id and some DO NOT.
As I said it returns the results as expected just looking to clean it up a little if there is a way.
Thank you in advance for your assistance!
Regards,
Ray
Shouldn't it be:
return Datatables::of(User::with('dealer', 'role'))->make(true);
More here: https://datatables.yajrabox.com/eloquent/relationships
Please or to participate in this conversation.