假设我在表中有7列,我想只选择其中的两列,就像这样

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

在laravel雄辩模型中,它看起来是这样的

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

但我猜这个表达式将选择id = 1的所有列,我只需要两列(姓名,姓氏)。如何只选择两列?


当前回答

如果您需要获取一个列,直接调用模型上的pluck是在Laravel中从所有模型中检索单个列的最有效的方法。

在拔之前调用get或all将在拔值之前将所有模型读入内存。

Users::pluck('email');

其他回答

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

你可以使用get()和all()

ModelName::where('a', 1)->get(['column1','column2']);

获取多列(返回集合):

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

如果你想把列作为数组使用下面的代码:

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

如果你想获得一个单列,试试这个:

Model::where('id', 1)->first(['column_name'])->column_name;

为了从表中获得特定列的结果,我们必须指定列名。

使用以下代码:-

   $result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();  

例如:

$result = DB::Table('Student')->select('subject','class')->where('id',1)->get();  

同样Model::all(['id'])->toArray()它将只获取id作为数组。