Select columns on relationship tables Hello,
Im looking for good way to make query with eager loader on relationship tables, but to take only columns that i need (select or pluck).
$parts = Parts::with('cars', 'bikes', 'formulas')->get();
This work but it returns too much data from relationship tables. How can I select for example just 2 columns to return data from this cars, bikes, formulas tables. Off course tables have same columns that Im trying to query (id, name).
Thank you
Hey,
try this:
$parts = Parts::with(['cars' => function ($query) {
$query->get(['column1', 'column2']);
}, 'bikes', 'formulas'])->get();
Cant test it right now. Hope that works. If get does not work, maybe there is another method for this scope.
Nah m8, still same result. I have tried also this:
$parts = Parts::with(
['cars' => function ($query) {
$query->select('id', 'name');
}],
['bikes' => function ($query) {
$query->select('id', 'name');
}],
['formulas' => function ($query) {
$query->select('id', 'name');
}]
)->get();
And Im getting good result (only id and name from cars table), but its only for cars, i have always null at bikes and formulas ..
You have to put in one array and not in 3,
$parts = Parts::with(
['cars' => function ($query) {
$query->select('id', 'name');
},
'bikes' => function ($query) {
$query->select('id', 'name');
},
'formulas' => function ($query) {
$query->select('id', 'name');
}]
)->get();
did not know select exists :D
I try the way you say, but in Laravel 8 return empty array, can you check? thanks.
@guc43 how can I put aliases in the columns?
@chrismark182 u need to include id from foreign table like $query->select('id', 'name','foreign_key');
You can try this simple syntax
$parts = Parts::with('cars:id,name', 'bikes:id,name', 'formulas:id,name')->get();
Please sign in or create an account to participate in this conversation.