可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
You can do it like this:
Table::select('name','surname')->where('id', 1)->get();
回答2:
Table::where('id', 1)->get(['name','surname']);
回答3:
By using all() method we can select particular columns from table like as shown below.
ModelName::all('column1', 'column2', 'column3');
Note: Laravel 5.4
回答4:
Also Model::all(['id'])->toArray()
it will only fetch id as array.
回答5:
You first need to create a Model, that represent that Table and then use the below Eloquent way to fetch the data of only 2 fields.
Model::where('id', 1)
->pluck('name', 'surname')
->all();
回答6:
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.
回答7:
You can use get() as well as all()
ModelName::where('a', 1)->get(['column1','column2']);
回答8:
Use following code : -
$result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();
回答9:
You can use Table::select ('name', 'surname')->where ('id', 1)->get ()
.
Keep in mind that when selecting for only certain fields, you will have to make another query if you end up accessing those other fields later in the request (that may be obvious, just wanted to include that caveat). Including the id field is usually a good idea so laravel knows how to write back any updates you do to the model instance.
回答10:
Also you can use pluck.
Model::where('id',1)->pluck('column1', 'column2');
回答11:
You can use the below query:
Table('table')->select('name','surname')->where('id',1)->get();
回答12:
->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
回答13:
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']);