mercredi 21 mars 2018

Cannot attach many to many using Pivot table - Laravel

I have a Vehicle and Product class.

A vehicle can have many products and a product can be in many vehicles.

I've made my pivot table in my migration:

public function up()
{
    Schema::create('product_vehicle', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('vehicle_id');
        $table->integer('product_id');
        $table->integer('amount_in_car');
        $table->timestamps();
    });
}

I also need to set some additional data to the Pivot table. The field amount_in_car.

In my Vehicle Model i've added my relations:

public function products() {
    return $this->belongsToMany(Product::class)->withTimestamps();
}

In my Product Model i've added my relations:

public function vehicles() {
    return $this->belongsToMany(Vehicle::class)->withTimestamps();
}

In my controller i try to attach a product to a vehicle and giving the additional fields:

    $validated = $request->validate([
        'amount_in_car' => 'required',
        'vehicle_id' => 'required'
    ]);

    $product = Product::find($product_id);

    $vehicle = Vehicle::find($validated['vehicle_id']);

    $vehicle->products()->attach($product, ['amount_in_car', $validated['amount_in_car']]);

I get this weird error where it is looking for a 0 field?

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `product_vehicle` (`created_at`, `product_id`, `updated_at`, `vehicle_id`, `0`, `1`) values (2018-03-21 13:49:12, 3, 2018-03-21 13:49:12, 1, amount_in_car, 13))

I tried using the ->save() instead of the ->attach().

But this doesn't work either, is there something wrong with my relationships?

Any help is appreciated.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2pxWEY2
via IFTTT

Aucun commentaire:

Enregistrer un commentaire