Eloquent 中 find 和 get 的区别 [英] the difference of find and get in Eloquent

查看:17
本文介绍了Eloquent 中 find 和 get 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i created 3 tables : users , roles and role_user.

用户模型:

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

没关系,我可以得到关系

it is ok, i can get the relation

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

但是当我改变了

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

未定义属性:IlluminateDatabaseEloquentCollection::$roles

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

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

推荐答案

get()

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

get()

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

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

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

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

等价于first()

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

Equivalent with first()

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

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

返回与

$user = User::find(1);

<小时>

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

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

这篇关于Eloquent 中 find 和 get 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆