简体   繁体   中英

Using a lookup table with Laravel's Eloquent ORM: not unique table alias?

I've been trying to use Eloquent for an application I'm making (being proted from Codeigniter) but I can't get it to work.

I have 3 tables:

  • users
  • departments
  • department_members (this is the lookup table)

department_members has 3 fields: id, department_id and user_id. All my tables have their own models. When I try to use the ORM to get the department of an user ( User::find(1)->member()->first() ) all I get is this error:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'users'

Although I know what the problem is, I don't know how to solve it, since it's all generated by the ORM.

The models:

  • Member model

     class Member extends Eloquent { public static $table = 'department_members'; public static $timestamps = false; public function user() { return $this->has_many_and_belongs_to('User', 'users'); } } 
  • User model

     class User extends Eloquent { public static $timestamps = false; public function member() { return $this->has_many_and_belongs_to('Member', 'department_members'); } } 
  • Department model

     class Department extends Eloquent { public function member() { return $this->has_many_and_belongs_to('Member', 'department_members'); } } 

The columns have appropiate names: id as PK, and the respective names with _id appended.

If more info is needed I would be happy to help out.

You've setup your relationships incorrectly. You don't need to have a member model - just a User, and Department model.

Like so:

# in User
public function departments() {
    return $this->has_many_and_belongs_to('Department', 'department_members');
}

# in Department
public function users() {
    return $this->has_many_and_belongs_to('User', 'department_members');
}

There's no need for the additional model. Additionally, you might want to read here: http://laravel.com/docs/database/eloquent#many-to-many - of special note is the pivot tables, in case you want to do some extra work on the join table aspect of the relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM