2

Is there a way to select only specific columns when using "with" with eloquent?

My problem is that i am getting a very long list of accounts and i also need to get their websites using the relation "with", but the "websites" object is big and it makes the request very slow.

I tried using:

$accounts = $accounts->with('websites')->select(['account_id','url']); 

And also:

$accounts = $accounts->with('websites', function($query) { $query->select(['account_id','url']); }); 

And they both didn't work.

I didn't see an answer for this in their documentation, so if there is a way i would really appreciate if someone would share it with me. Also if there is an alternative for "with" that can give the same result it will be great as well. Thanks.

2 Answers 2

8
$accounts = $accounts->with([ 'websites' => function($query) { $query->select(['account_id','url']); } ]); 
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this in fact does work if and only if the foreign key that links the two tables is included in the select (inside the with or outside, if you select specific columns from the main table). If the foreign key is missing, the whole thing will fail (returning null for the "with" table) silently, without any hint what is wrong.
3

Try to define the columns on your relationship:

class Account { public function websites() { return $this->hasMany('App\Website')->select(['account_id','url']); } } 

Please note that the class and the relation is only for demonstrating purposes, try to add this ->select(['account_id','url']) on your relation.

2 Comments

but what if I want to sometimes select these columns, and sometimes others? how to define it outside the model?
@Tom, check the other answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.