假设我在表中有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的所有列,我只需要两列(姓名,姓氏)。如何只选择两列?
当前回答
获取一列的值:
Table_Name::find($id)->column_name;
你可以用where子句来使用这个方法:
Table_Name::where('id',$id)->first()->column_name;
或者使用这个方法来绕过PhpStorm“在应用程序\模型中没有找到的方法”:
Table_Name::query()->where('id','=',$id)->first()->column_name;
在查询生成器中:
DB::table('table_names')->find($id)->column_name;
带where从句:
DB::table('table_names')->where('id',$id)->first()->column_name;
or
DB::table('table_names')->where('id',$id)->first('column_name');
最后一个方法的结果是数组
其他回答
获取一列的值:
Table_Name::find($id)->column_name;
你可以用where子句来使用这个方法:
Table_Name::where('id',$id)->first()->column_name;
或者使用这个方法来绕过PhpStorm“在应用程序\模型中没有找到的方法”:
Table_Name::query()->where('id','=',$id)->first()->column_name;
在查询生成器中:
DB::table('table_names')->find($id)->column_name;
带where从句:
DB::table('table_names')->where('id',$id)->first()->column_name;
or
DB::table('table_names')->where('id',$id)->first('column_name');
最后一个方法的结果是数组
你可以这样做:
Table::select('name','surname')->where('id', 1)->get();
->get()很像->all()(和->first()等)可以把你想带回的字段作为参数;
- > /所有([' column1 ', ' column2 '])
会带回集合,但只与列n1和列2
首先需要创建一个Model,表示该表,然后使用下面的Eloquent方法仅获取2个字段的数据。
Model::where('id', 1)
->pluck('name', 'surname')
->all();
use App\Table;
// ...
Table::where('id',1)->get('name','surname');
如果没有哪里
Table::all('name','surname');