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

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

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

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

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


当前回答

use App\Table;
// ...
Table::where('id',1)->get('name','surname');

如果没有哪里

Table::all('name','surname');

其他回答

你可以使用下面的查询:

Table('table')->select('name','surname')->where('id',1)->get();

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

使用以下代码:-

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

例如:

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

如果您想从数据库中获取单个值

    Model::where('id', 1)->value('name');

->get()很像->all()(和->first()等)可以把你想带回的字段作为参数;

- > /所有([' column1 ', ' column2 '])

会带回集合,但只与列n1和列2

你可以这样做:

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