Laravel Eloquent: How to Get Only Certain Columns from Joined Tables

Laravel with([]) select only some columns of the relation

Like this:

$order = Order::with([
'company:id,name,size',
'complaints:id,name,body',
'person',
'items',
'items.product:id,name,price',
'items.product.stockManagement',
'status:id',
'items.product.media',
'items.product.mainProduct',
'items.product.mainProduct.media'
])->findOrFail($id);

The documentation is very brief about the loading of specific columns (you even have to scroll down a bit to the heading that says "Eager Loading Specific Columns").

You may not always need every column from the relationships you are retrieving. For this reason, Eloquent allows you to specify which columns of the relationship you would like to retrieve:

$books = App\Book::with('author:id,name')->get();

Note:

When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve.

How to select specific columns in laravel eloquent

You can do it like this:

Table::select('name','surname')->where('id', 1)->get();

How to select columns from joined tables: laravel eloquent

Finally found it..
In the ->get() you have to put the 'staff_id' like this

Vehicle::where('id',1)
->with(['staff'=> function($query){
// selecting fields from staff table
$query->select(['staff.id','staff.name']);
}])
->get(['id','name','staff_id']);

Since I didn't take the staff_id, it couldn't perform the join and hence staff table fields were not shown.

Get Specific Columns Using “With()” Function in Laravel Eloquent

Well I found the solution. It can be done one by passing a closure function in with() as second index of array like

Post::query()
->with(['user' => function ($query) {
$query->select('id', 'username');
}])
->get()

It will only select id and username from other table. I hope this will help others.


Remember that the primary key (id in this case) needs to be the first param in the
$query->select() to actually retrieve the necessary results.*

Laravel - Select only specified columns in joined tables

Change your model class as per your requirements to specify what columns you want selected:

public function someModel() {
return $this->belongs_to('otherModel')->select(array('id', 'name'));
}

Laravel 5 Eloquent scope join and select specific columns

You may try this:

->select('accounts.*', 'users.id as uid','users.user_name');


Related Topics



Leave a reply



Submit