Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...