Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

laravel - the difference of find and get in Eloquent

i created 3 tables : users , roles and role_user.

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: IlluminateDatabaseEloquentCollection::$roles

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

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.

Uses

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

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();

returns the same as

$user = User::find(1);

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...