php 如何在 Laravel Eloquent 中选择某些字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28530364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Select Certain Fields in Laravel Eloquent?
提问by rkaartikeyan
How to Do following Query in Laravel Eloquent?
如何在 Laravel Eloquent 中执行以下查询?
SELECT catID, catName, imgPath FROM categories WHERE catType = "Root"
I have tried following
我试过跟随
CategoryModel::where('catType', '=', 'Root')
->lists('catName', 'catID', 'imgPath');
but its return only two fields.
但它只返回两个字段。
Array ( [7] => Category 1 )
回答by lukasgeiter
lists()
turns the resulting collection into an array with key value. You can only have two database columns in there. Otherwise you have to use select()
but then you will get a collection of models not just an array.
lists()
将结果集合转换为具有键值的数组。那里只能有两个数据库列。否则你必须使用select()
但是你会得到一个模型集合而不仅仅是一个数组。
$categories = CategoryModel::select('catID', 'catName', 'imgPath')
->where('catType', '=', 'Root')
->get();
回答by Harry Bosh
Selecting multiple columns
选择多列
CategoryModel::get(['catName', 'catID', 'imgPath']);
Works with Laravel 5.3 too!
也适用于 Laravel 5.3!
回答by Khan Shahrukh
CategoryModel::wherecatType('Root')
->pluck('catName', 'catID', 'imgPath');
回答by Haritsinh Gohil
If you want to get certain columns then You can use one of the two method get()
or all()
如果您想获取某些列,则可以使用两种方法之一get()
或all()
but the syntax is different for both, get()
method takes array
as argumentand all()
method takes string
or array
both as argument:
但两者的语法不同,get()
方法array
作为参数和all()
方法采用string
或array
两者都作为参数:
Model::all('field1','field2')with string
as arguments
型号::所有(“字段1”,“字段2”)与string
作为参数
CategoryModel::all('catName', 'catID', 'imgPath')->where('catType','Root');
Model::all(['field1','field2'])with array
as arguments
模型::所有([ 'field1的', 'FIELD2'])与array
作为参数
CategoryModel::all(['catName', 'catID', 'imgPath'])->where('catType','Root');
Model::get(['field1','field2'])
模型::get(['field1','field2'])
CategoryModel::get(['catName', 'catID', 'imgPath'])->where('catType','Root');
回答by lewis4u
From laravel version 5.3^ lists()
is deprecated and function pluck()
is used instead.
从 laravel 5.3^ 版本开始lists()
不推荐pluck()
使用,而是使用函数。
pluck()
returns a collection and if you need a simple array just prepend ->toArray()
to it.
pluck()
返回一个集合,如果你需要一个简单的数组,只需->toArray()
在它前面加上。