I’m trying to select a specific column from a relationship.
F.x
User::with(array('phone' => function($q) {
$q->where('ext', "!=" 42);
}))->select('id', 'number');
Here i ONLY want to select the user ID, and the number for the phone.
How can i do that?
Keep in mind, there is over 2m users and 100m numbers, which is why i only want the user id and the number.
3
Answers
Please try:
Or
You can achieve this by making use of the
select
method within yourwith
clause, specifying only the columns you are interested in. Additionally, you might need to add the foreign key to the select method to preserve the relationship linkage.For your specific case, your Eloquent query should look something like this:
In this query,
id,
number,
anduser_id
in theselect
method of the phone relationship are the columns from the phones table, while theid
in theselect
method outside the with clause is from theusers
table.Note that it’s essential to include the foreign key
(user_id)
in theselect
method within the with clause. This is because Eloquent needs this to match the related models back onto their parent models.Also, remember that the
with
method does eager loading, which means it will fetch all related phones that meet the criteria for all users, not just the first one that matches.If you’re working with very large datasets, it might be more efficient to consider database indexing strategies, using chunks or even directly using a
JOIN
with a raw query. These can all be done within Laravel, and might be better suited for your use case, depending on your exact needs.