3
votes

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.

1
The error doesn't seem to have anything to do with relations. Somewhere in your code an object is converted to a string. Have a look at the error message, there should be filename and line number where the error occurs. Please paste that part of the code.jedrzej.kurylo
What happens when you return dd($things)? $user->things()` returns an instance of Collection. Use dynamic attribute instead and see if works: $things = $user->things; or $things = $user->things->first();CrackingTheCode

1 Answers

4
votes

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().