laravel Eloquent 中 find 和 get 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27598603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:34:40  来源:igfitidea点击:

the difference of find and get in Eloquent

laraveleloquent

提问by huangwei jie

i created 3 tables : users , roles and role_user.

我创建了 3 个表:用户、角色和角色用户。

the user model :

用户模型:

public function roles()
{
    return $this->belongsToMany('Role');
}

it is ok, i can get the relation

没关系,我可以找到关系

$roles = User::find(1)->roles;

But when i changed

但是当我改变

$roles = User::where('name', 'Test')->get()->roles;

Undefined property: Illuminate\Database\Eloquent\Collection::$roles

Undefined property: Illuminate\Database\Eloquent\Collection::$roles

So that is some wrong or 'find', 'where' is difference ? if i want use where for fetch relation , how can i do ?

所以这是一些错误或“找到”,“哪里”的区别?如果我想使用 where 获取关系,我该怎么做?

回答by lukasgeiter

get()

get()

get()simply executes whatever (select) query you have built. It will return a collection(Illuminate\Database\Eloquent\Collection) in any case. That's the reason for your error message. You want the $rolesof one model but you are trying to get it from a collection, which is obviously not possible.

get()只需执行您构建的任何(选择)查询。在任何情况下,它都会返回一个集合( Illuminate\Database\Eloquent\Collection)。这就是您的错误消息的原因。您想要$roles一个模型的 ,但您试图从集合中获取它,这显然是不可能的。

find()

find()

find()is used to fetch one or manymodels by its / their primary key(s). The return value will either be a single model, a collection or nullif the record is not found.

find()用于通过其/它们的主键获取一个或多个模型。返回值将是单个模型、集合或未找到记录。null

Uses

用途

$user = User::find(1); // returns model or null
$users = User::find(array(1, 2, 3)); // returns collection

Equivalent with first()

相当于 first()

first()returns the first record, so you get a single model even if the result may would contain multiple records

first()返回第一条记录,因此即使结果可能包含多条记录,您也会得到一个模型

$user = User::where('id', 1)->first();

returns the same as

返回与

$user = User::find(1);


Meaning for your case you want to use first()instead of get()

对于您要使用的情况first()而不是get()

$roles = User::where('name', 'Test')->first()->roles;

回答by Jarek Tkaczyk

getreturns a collection, findreturns single model. So obviously you can't call ->nameon the collection of users.

get返回一个集合,find返回单个模型。所以显然你不能调用->name用户的集合。

User::find(1); // single User model
User::find([1,2,3]); // collection of User models
User::get(); // collection of User models

There are also other methods returning the query result, eg.:

还有其他返回查询结果的方法,例如:

User::first(); // single User model
User::pluck('name'); // single value of name field of the first row

and so on.. read the docs

等等..阅读文档