I have 3 tables called permissions
, processes
and permission_processes
.
The tables' data look like this:
permissions
-----------
ID Name
-- ----
1 Blog
2 Users
...
processes
---------
ID Name
-- ----
1 Create
2 Update
3 View
4 Delete
permission_processes
--------------------
ID permission_id process_id
-- ------------- ----------
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
6 2 2
...
I am trying to get all processes for a specific permission. However, when using relationships in the models, it is looking at the permissions
table's primary key
as a table.
Here is the error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'ahp.permission_id' doesn't exist (SQL: select `permission_processes`.*,
`permission_id`.`permission_id` as `pivot_permission_id`,
`permission_id`.`permission_process_id` as `pivot_permission_process_id`
from `permission_processes` inner join `permission_id` on
`permission_processes`.`permission_process_id` = permission_id`.`permission_process_id` where
`permission_id`.`permission_id` = 0O9aynuPJtBjdYW)
Here are each of the models:
Permission:
class Permission extends Model
{
protected $table = 'permissions';
protected $primaryKey = 'permission_id';
protected $fillable = ['permission_id', 'permission_name', 'permission_description', 'permission_slug', 'state', 'active'];
public function permission_processes() {
return $this->belongsToMany('\App\PermissionProcess', 'permission_id', 'permission_id');
}
}
PermissionProcess:
class PermissionProcess extends Model
{
protected $table = 'permission_processes';
protected $primaryKey = 'permission_process_id';
protected $fillable = ['permission_process_id', 'permission_id', 'process_id', 'state', 'active'];
public function process() {
return $this->hasOne('\App\Process', 'process_id', 'process_id');
}
public function permission() {
return $this->hasOne('\App\Permission', 'permission_id', 'permission_id');
}
}
Process:
class Process extends Model
{
protected $table = 'processes';
protected $primaryKey = 'process_id';
protected $fillable = ['process_id', 'process_name', 'process_description', 'state', 'active'];
public function permission_processes() {
return $this->belongsToMany('\App\PermissionProcess', 'process_id', 'process_id');
}
}
Here is the code I am using to call the permission processes
:
$all_permissions = \App\Permission::orderBy('active', 1)->get();
dd($all_permissions->first()->permission_processes);
What am I doing wrong? All my other relationships using the same process works?
Laravel automatically looks for the linking table.
You need to tell it what the other side of the link will be so that it can guess the column names in the linking table.
class Permission extends Model {
public function processes() {
return $this->belongsToMany('\App\Permission', 'your_link_table_name', 'key_1','key_2');
}
}
If you later need the middle table you will use $permission->processess->pivot