假设我在表中有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的所有列,我只需要两列(姓名,姓氏)。如何只选择两列?
当前回答
你也可以在这里使用findOrFail()方法,它很好用
如果没有捕获异常,则自动向用户发送404 HTTP响应。当使用这些方法不给出500错误时,没有必要编写显式检查来返回404响应。
ModelName::findOrFail($id, ['firstName', 'lastName']);
其他回答
虽然最常见的方法是使用Model::select, 它可能导致在模型类中呈现用访问器方法定义的所有属性。如果你在模型中定义attribute:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the user's first name.
*
* @param string $value
* @return string
*/
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}
然后使用: 表名::选择(“用户名”)- >(“id”,1)- > ();
它将输出带有first_name和用户名的集合,而不是只有用户名。
最好单独使用pluck(),如果需要特定的列,可以选择与select结合使用。
TableName::select('username')->where('id', 1)->pluck('username');
or
表名::(“id”,1)- >拔(“用户名”);//返回只包含用户名值的集合
另外,可以选择使用->toArray()将集合对象转换为数组。
如果您想获取单行,并从该行单列中获取特定列的值,只需使用find()方法,并指定要检索的列。
下面是示例代码:
ModelName::find($id_of_the_record, ['column_name'])->toArray()['column_name'];
获取多列(返回集合):
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;
你可以这样做:
Table::select('name','surname')->where('id', 1)->get();
同样Model::all(['id'])->toArray()它将只获取id作为数组。