简体   繁体   English

在 Eloquent ORM 中使用 find 选择特定的列

[英]Select specific columns using find in Eloquent ORM

In Laravel how can I get specific columns using find?在 Laravel 中,如何使用查找获取特定列? 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?有没有办法用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() :首先,您可以将要选择的列作为第二个参数传递给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.).其次,尽管有些特殊, find()只是用于执行查询的方法,因此您可以事先正常修改查询(添加 selects、wheres、orders 等)。 Therefore, you can just add a select() before you execute the find() :因此,您可以在执行find() select() ) :

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

Here is another way, similar to @patricus.这是另一种方式,类似于@patricus。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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