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

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

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

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

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


当前回答

你可以使用下面的查询:

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

其他回答

你可以这样做:

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

如果你想获取单列的值,比如'name',你也可以使用下面的方法:

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

你可以使用Table::select ('name', '姓氏')->where ('id', 1)->get()。

请记住,当只选择某些字段时,如果您最终在请求中访问那些其他字段,则必须进行另一个查询(这可能是显而易见的,只是想包括这个警告)。包含id字段通常是一个好主意,这样laravel就知道如何回写您对模型实例所做的任何更新。

你可以得到它

`PostModel::where('post_status', 'publish')->get(['title', 'content', 'slug', 'image_url']`)

link

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