1

I have checked many solutions to get specific columns from first model with eager loading but nothing works in my case.

for example: I want specific columns from model User and want to get relationship data with eager loading without any join.

$users= User::select('name') // get one column from user table
->with(array('role_user' => function($query){
    $query->select('role_name'); // and select one column from pivot table
}))
->paginate(3);

when I don't use User::select('name), it returns relationship data with eager load when I use select, it returns empty array.

How I can get specific columns from both tables using eager loading

1
  • 1
    You should always also select the primary and foreign keys when using eager loading Commented Jul 27, 2021 at 7:44

2 Answers 2

3

I don't exactly know, how you defined your relationship but Laravel has some weird behavior: You should always also select the primary and foreign keys:

$users= User::select(['id', 'name']) // get one column from user table
->with(array('role_user' => function($query){
    $query->select(['id', 'role_name']); // and select one column from pivot table
}))
->paginate(3);

You can simplify it to this:

$users= User::select(['id', 'name']) // get one column from user table
->with(['role_user:id,user_id,role_name']) // and select one column from pivot table
->paginate(3);
Sign up to request clarification or add additional context in comments.

4 Comments

it is also returning empty array in relations but (id, name) columns from User model
Can you edit your question and add the schema of the two tables plus the relationship from the model? You probably need to add user_id to the select() inside with()
@shaedrich thanks! it worked. foreign key is required
If you're reading this in the future, checkout the weird behaviour. This answer addresses this issue well and resolved my issue.
0

We Never Know the schemas and the relationships of your project.. But I assume You This Should Work

$users = User::select('id','name') 
               ->with(['role_user:id,user_id,role_name'])
               ->paginate(3);

In your User Model Relationships must be

public function role_user(){
return $this->belongsToMany(Role::class, 'role_user'); // pivot table name
}

In your Role Model

 public function users(){
return $this->belongsToMany(User::class, 'role_user'); // pivot table name
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.