Laravel 5 belongsToMany() on custom table

时间:2015-08-14 22:43:56

标签: php laravel laravel-5 eloquent

I'm using custom made tables. It is simple user role feature. But not using conventional Eloquent database schema style.

Table User

  1. userId(PK)
  2. userName (varchar)

Table Role

  1. roleId (PK)
  2. roleName (varchar)

Table userrole pivot column

  1. userroleId
  2. roleId
  3. userId

Now I've Model User which has this method

    public function roles()
{
    return $this->belongsToMany("App\Role", "userrole", "roleId", "userId");
}

When I make call like this it gives error

$roles = App\User::where("userId", "1")->first()->roles;
dd($roles);

Error it displays is:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'role.id' in 'on clause' (SQL: select `role`.*, `userrole`.`roleId` as `pivot_roleId`, `userrole`.`userId` as `pivot_userId` from `role` inner join `userrole` on `role`.`id` = `userrole`.`userId` where `userrole`.`roleId` is null)

Here's my humble request. Please don't suggest to change the table schema. I can't. I'm stuck with this. Thank you!

1 个答案:

答案 0 :(得分:3)

您是否已在" userrole"上设置了主键。模型?

Laravel自动假设您的主键名为id

请参阅:http://laravel.com/docs/5.1/eloquent

看一下主键部分:

  

Eloquent还会假设每个表都有一个主键列   名为id。您可以定义$primaryKey属性来覆盖它   约定。

尝试在userrole模型中覆盖它,如下所示:

protected $primaryKey = 'roleId';

尽量仔细阅读所有文件。