Drennos
Drennos

Reputation: 313

Seeding Relationship one to many in Laravel

I need to seed a relationship in Laravel, where each user has many devices

The User model

public function devices()
{
    return $this->hasMany(Device::class);
}

The Device model

public function users()
{
    return $this->belongsTo(User::class);
}

}

The device_user table

    Schema::create('device_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('device_id')->unsigned()->index();
        $table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });

The seeder

    factory(App\Device::class, 20)->create()->each(function(App\Device $device) {
        $device->users()->attach([
            rand(1,5), 
            rand(6,15), 
            rand(16,20), 
        ]);
    });

But, when I run the migration with seeder, I get this message

    Call to undefined method Illuminate\Database\Query\Builder::attach()

Please, help

Upvotes: 1

Views: 2199

Answers (1)

Abdi
Abdi

Reputation: 608

attach for many to many relationships, you don't need device_user table for one to many relationship, in one to many you should create a column with name user_id in device table and just it. after that you can insert data in device table with user_id. and get user relationship with

Device::user()->get();

Upvotes: 3

Related Questions