0

I have a pivot model for a Many-to-Many relationship called UserWebpage.

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserWebpage extends Pivot
{
    public function collections(){
        return $this->belongsToMany('App\Collection', 'collection_user_webpage');
    }
}

I also have a model called Collection

namespace App;

use Illuminate\Database\Eloquent\Model;

class Collection extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function userWebpages(){
        return $this->belongsToMany('App\UserWebpage', 'collection_user_webpage');
    }
}

I'm trying to establish a Many-to-Many relationship between UserWebpage and Collection. I know something like this should be possible based on this SO question that I found: Laravel: How to use multiple pivot table relationships

My issue is this:

When I try to insert a relationship between a UserWebpage instance and a Collection instance, I get the following error.

Code to insert the relationship:

App\UserWebpage::where('user_id', $user->id)->take(2)->get()->each(function($user_webpage) use ($user){
    $collection = factory(App\Collection::class)->create(['user_id' => $user_webpage->user_id]);
    $collection->userWebpages()->attach($user_webpage->id);
});

The error I get:

Illuminate\Database\QueryException : SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'field list' (SQL: insert into collection_user_webpage (``, collection_id) values (1, 1))

Is it possible to create this type of a relationship? Or am I missing something?

szk5
  • 3
  • 1
  • what is your collection and user primary key? – usrNotFound Jul 24 '18 at 23:18
  • you've said *Many to many relatonship bet. UserWebpage and Collection* but your `UserWebpage` is extending the `Pivot` model class? why? – Wreigh Jul 25 '18 at 00:52
  • @usrNotFound My Collection primary key is collection_id and for UserWebpage it's user_webpage_id. – szk5 Jul 25 '18 at 13:39
  • @Wreigh I wanted to use a Pivot Model class. UserWebpage represents a relationship and in order to use it in another relationship, I created a Pivot Model class for it. It's described in the Laravel docs in [this page](https://laravel.com/docs/5.6/eloquent-relationships#many-to-many), under "Defining Custom Intermediate Table Models" – szk5 Jul 25 '18 at 13:41

1 Answers1

0

The default value for $foreignPivotKey doesn't work in Pivot, you have to explicitly specify it:

public function collections(){
    return $this->belongsToMany('App\Collection', 'collection_user_webpage', 'user_webpage_id');
}
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
  • Thank you, a version of this worked for me. Basically, I had to do this in userWebpages method on the Collection class. After specifying the 3rd and 4th arguments, I was able to insert relationships between a Collection instance and a UserWebpage instance. – szk5 Jul 25 '18 at 13:51