简体   繁体   中英

Select specific columns using find in Eloquent ORM

In Laravel how can I get specific columns using find? I know you can do it with get like this:

$user = User::where('u_id', '=', 1)
        ->get(['firstname', 'lastname']);

Is there a way to do it with find? This is what I currently have:

$user = User::find(1);

You have two options.

First, you can pass the columns to select as the second parameter to find() :

$user = User::find(1, ['firstname', 'lastname']);

Second, although somewhat specialized, find() is just the method used to execute the query, so you can modify the query as normal beforehand (add selects, wheres, orders, etc.). Therefore, you can just add a select() before you execute the find() :

$user = User::select(['firstname', 'lastname'])->find(1);

Here is another way, similar to @patricus.

$did = User::findOrFail($id, ['first_name', 'last_name']);

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