0

I have two models Status and StatusCategory which have a belongToMany relationship. I have a pivot table status_status_category with two fields status_id and status_category_id I have also made these two fields the primary key.

I have created model factories for my Status and StatusCategoryModel. When I ty to seed them I get the following exception in the terminal output:

Exception : Property [id] does not exist on this collection instance.

Relevant code is as follows:

    $factory->define(App\Status::class, function (Faker $faker) {
    return [
        'name' => $faker->word
    ];
});


$factory->define(App\StatusCategory::class, function (Faker $faker) {
    return [
        'name' => $faker->word
    ];
});

public function statuses() {
        return $this->belongsToMany( Status::class );
    }

public function statusCategories() {
        return $this->belongsToMany( StatusCategory::class );
    }

factory( Status::class, 30 )->create()->each( function ( $u ) {
            $u->statusCategories()->save( factory( StatusCategory::class )->make() );
        } );

I'm not sure where to turn here to be honest, if anyone can help? Thanks

showFocus
  • 701
  • 2
  • 8
  • 21

1 Answers1

0

You can create pivot model to seed the pivot table. Here is an example:

Status Model

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Status extends Model{
    protected $table='statuses';
    protected $fillable = [
        'something you want to fill'
    ];

    public function statusStatusCategories(){
        return $this->belongsToMany(StatusCategory::class);
    }
}

StatusCategory Model

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class StatusCategory extends Model{
    protected $table='status_categories';
    protected $fillable = [
        'something you want to fill'
    ];

    public function statuses(){
        return $this->belongsToMany(Status::class);
    }
}

For the pivot

namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;

class StatusStatusCategory extends Pivot
{
    protected $table='status_status_category';
    protected $fillable = [
        'status_id','status_category_id'
    ];

    public function status(){
        return $this->hasOne(Status::class, 'id', 'status_id');
    }

    public function statuscategory(){
    return $this->hasOne(StatusCategory::class, 'id', 'statuscategory_id');
    }
}

Hope this helps.

Foysal Nibir
  • 543
  • 4
  • 14