发现和获得在雄辩中的区别 [英] the difference of find and get in Eloquent

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

问题描述

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

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;

未定义的属性: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 ?

推荐答案

get()



get()只需执行你所建立的任何(选择)查询。无论如何,它将返回一个集合 Illuminate\Database\Eloquent\Collection )。这就是你的错误信息的原因。你想要一个模型的 $ roles ,但是你试图从一个集合中获取它,这显然是不可能的。

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 $roles of one model but you are trying to get it from a collection, which is obviously not possible.

find()用于通过其/ strong>主键来获取一个或多个模型。如果没有找到记录,返回值将是单个模型,集合或 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;

这篇关于发现和获得在雄辩中的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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