简体   繁体   中英

Laravel Eloquent ORM - Is it possible set default select columns list?

In much of db queries I did not need all data, so I do the following

User::get(array('id', 'first_name', 'email'));

Is it possible set to select by default ('id', 'first_name', 'email') columns.

You can use Eloquent Query Scope Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope

For example in your User model add this method

public function scopeFetch($query, $columns = array('id', 'first_name', 'email'))
{
    return $query->get($columns);
}

and call it this way

User::fetch();

You can simply define a scope function inside your model class.

public function scopeGetData($query)
{
    return $query->select(['id', 'first_name', 'email']);
}

you can call this scope in your controller function like this

User::GetData()->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM