Search code examples
laravelforeign-keyseloquentlaravel-5

Laravel, Eloquent n:m relationship


I try do define a n:m relationship in Laravel using Eloquent. I have the following tables given:

users:

  • ID
  • foo

things

  • ID

users_things

  • thing_id
  • foo

In my User Model I have defined the following relation

public function things() {
  return $this->hasMany('App\Thing', 'user_things', 'foo', 'thing_id');
}

In the Things Model is the counterpart

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

When I call in the Controller

$user = User::find(1) //works
//$thing = Thing::find(1) works
$things = $user->things();
return $things

I get the following message:

Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string.

My problem is that, I cannot use the User ID as foreign key in the combination table. It has to be the foo column.


Solution

  • You may try this (Use belongsToMany for many-to-many relationship):

    // User.php
    
    protected $primaryKey = 'foo';
    public $incrementing = false;
    
    public function things() {
        return $this->belongsToMany('App\Thing', 'user_things', 'foo', 'thing_id');
    }
    
    // Thing.php
    public function users() {
        return $this->belongsToMany('App\User', 'user_things', 'thing_id', 'foo');
    }
    

    Finally, use $user->things instead of $user->things().