假设我在表中有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的所有列,我只需要两列(姓名,姓氏)。如何只选择两列?
当前回答
同样Model::all(['id'])->toArray()它将只获取id作为数组。
其他回答
通过使用all()方法,我们可以从表中选择特定的列,如下所示。
ModelName::all('column1', 'column2', 'column3');
注意:Laravel 5.4
首先需要创建一个Model,表示该表,然后使用下面的Eloquent方法仅获取2个字段的数据。
Model::where('id', 1)
->pluck('name', 'surname')
->all();
你也可以用勇气。
Model::where('id',1)->pluck('column1', 'column2');
同样Model::all(['id'])->toArray()它将只获取id作为数组。
你可以得到它
`PostModel::where('post_status', 'publish')->get(['title', 'content', 'slug', 'image_url']`)
link