Benyi
Benyi

Reputation: 952

Laravel 5.2 Auth::User Foreign Key Join Query

I'm new to Laravel.

I add a new column named permission in default User table. And it's a foreign key related to p_id in Permissions table (user.permission = permissions.p_id)

One user belongs to a Permission grade (p_id), but a Permission grade can be belonged to many users.

[DB FIELDS]

user
- ...
- permission

permission 
- p_id
- p_permission
- p_title

And my Eloquent Model definition

[App\Permission]

public function user() {
    return $this->hasMany('App\Permission', 'p_id');
}
[App\User]

public function permission() {
    return $this->belongsTo('App\Permission', 'permission', 'p_id');
}

In Controller, how do I query p_title or other permission.* fields?

I've tried

echo Auth::User()->permission->p_title;
echo User::find(1)->permission->p_title;

both are return Trying to get property of non-object,

And

echo Auth::User()->with('permission')->get();

returns all the users. (What I want is the logged in user)

How can I query Auth::User() with foreign key just like use Auth::User()->p_title as easy?

Thank you so much.

Upvotes: 1

Views: 1415

Answers (2)

Parithiban
Parithiban

Reputation: 1656

Can You Check this in your permission model

App/Permission

protected $table = 'Permission';
protected $primaryKey = 'p_id';

Upvotes: 0

linuxartisan
linuxartisan

Reputation: 2426

Your Permission model relation is incorrect.

[App\Permission]

public function users() {
    return $this->hasMany('App\User', 'permission');
}

Upvotes: 1

Related Questions