how to select specific columns in laravel eloquent

2019-03-08 12:48发布

lets say I have 7 columns in table, and I want to select only two of them, something like this

SELECT `name`,`surname` FROM `table` WHERE `id` = '1';

In laravel eloquent model it may looks like this

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

but I guess this expression will select ALL columns where id equals 1, and I want only two columns(name, surname). how to select only two columns?

13条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-08 13:00

You can use the below query:

Table('table')->select('name','surname')->where('id',1)->get();
查看更多
We Are One
3楼-- · 2019-03-08 13:01

->get() much like ->all() (and ->first() etc..) can take the fields you want to bring back as parameters;

->get/all(['column1','column2'])

Would bring back the collection but only with column1 and column2

查看更多
小情绪 Triste *
4楼-- · 2019-03-08 13:02

By using all() method we can select particular columns from table like as shown below.

ModelName::all('column1', 'column2', 'column3');

Note: Laravel 5.4

查看更多
太酷不给撩
5楼-- · 2019-03-08 13:04

You can also use find() like this:

ModelName::find($id, ['name', 'surname']);

The $id variable can be an array in case you need to retrieve multiple instances of the model.

查看更多
乱世女痞
6楼-- · 2019-03-08 13:04

you can also used findOrFail() method here it's good to used

if the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these method not give a 500 error..

ModelName::findOrFail($id, ['firstName', 'lastName']);
查看更多
爷、活的狠高调
7楼-- · 2019-03-08 13:06

Also you can use pluck.

Model::where('id',1)->pluck('column1', 'column2');
查看更多
登录 后发表回答