假设我在表中有7列,我想只选择其中的两列,就像这样
SELECT `name`,`surname` FROM `table` WHERE `id` = '1';
在laravel雄辩模型中,它看起来是这样的
Table::where('id', 1)->get();
但我猜这个表达式将选择id = 1的所有列,我只需要两列(姓名,姓氏)。如何只选择两列?
假设我在表中有7列,我想只选择其中的两列,就像这样
SELECT `name`,`surname` FROM `table` WHERE `id` = '1';
在laravel雄辩模型中,它看起来是这样的
Table::where('id', 1)->get();
但我猜这个表达式将选择id = 1的所有列,我只需要两列(姓名,姓氏)。如何只选择两列?
当前回答
为了从表中获得特定列的结果,我们必须指定列名。
使用以下代码:-
$result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();
例如:
$result = DB::Table('Student')->select('subject','class')->where('id',1)->get();
其他回答
你可以得到它
`PostModel::where('post_status', 'publish')->get(['title', 'content', 'slug', 'image_url']`)
link
如果你想获取单列的值,比如'name',你也可以使用下面的方法:
Table::where('id', 1)->first(['name'])->name;
在laravel 5.3中,只有使用get()方法,你才能获得表的特定列:
YouModelName::get(['id', 'name']);
或者在laravel 5.4中,你也可以使用all()方法来获取你选择的字段:
YourModelName::all('id', 'name');
对于上面的get()或all()方法,你也可以使用where(),但两者的语法不同:
模型::所有()
YourModelName::all('id', 'name')->where('id',1);
模型:get ()
YourModelName::where('id',1)->get(['id', 'name']);
如果您需要获取一个列,直接调用模型上的pluck是在Laravel中从所有模型中检索单个列的最有效的方法。
在拔之前调用get或all将在拔值之前将所有模型读入内存。
Users::pluck('email');
如果您想获取单行,并从该行单列中获取特定列的值,只需使用find()方法,并指定要检索的列。
下面是示例代码:
ModelName::find($id_of_the_record, ['column_name'])->toArray()['column_name'];