dimanche 12 février 2017

Laravel Defining Custom Intermediate Table Models

I'm trying to get the user permissions by using Eloquent

I have 3 tables,

the first is the users table,

the second is the permissions table

and the third is user_permissions

the structure is very simple

users
-id
-name

permissions
-id
-name

user_permissions
-user_id
-permission_id
-read
-write
-update
-delete

this is the code that display the user permissions:

$user = App\User::find(1)->first();
foreach($user->permissions as $permission){
    echo "Read".$permission->pivot->read."<br>";
    echo "Write".$permission->pivot->write."<br>";
    echo "Update".$permission->pivot->update."<br>";
    echo "Delete".$permission->pivot->delete."<br>";
}

it all works fine when I define the relationships this way ( in the user model):

public function permissions()
{
    return $this->belongsToMany('App\Permission','user_permissions')->withPivot('read', 'create','update','delete');
}

but I want to write it in another way because I don't want to choose the fields that I need I just want to choose them all so when I write it like this I get an error:

public function permissions()
{
    return $this->belongsToMany('App\Permission','user_permissions')->using('App\UserPermission');
}

and this is my error:

BadMethodCallException in Builder.php line 2440: Call to undefined method Illuminate\Database\Query\Builder::using()



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kHjPO8
via IFTTT

Aucun commentaire:

Enregistrer un commentaire