在大多数数据库查询中,我不需要所有数据,所以我执行以下操作
User::get(array('id', 'first_name', 'email'));
是否可以设置为默认选择("id"、"first_name"、"电子邮件")列。
您可以使用雄辩的查询范围 作用域允许您轻松地在模型中重用查询逻辑。若要定义作用域,只需在模型方法前面加上作用域
例如,在您的User
模型中添加此方法
public function scopeFetch($query, $columns = array('id', 'first_name', 'email'))
{
return $query->get($columns);
}
并这样称呼它
User::fetch();
您可以简单地在模型类中定义一个作用域函数。
public function scopeGetData($query)
{
return $query->select(['id', 'first_name', 'email']);
}
您可以在控制器函数中调用此作用域,如下所示
User::GetData()->get();