mercredi 5 décembre 2018

Laravel 5.7: Eloquent Pivot fields not being casted with sync()

I have the following Eloquent Models with a many to many relationship:

class User extends Model 
{
    public function products() 
    {
        return $this->belongsToMany(Product::class)
            ->using('App\UserProductPivot')
            ->withPivot('label', 'is_primary', 'sort_order')
    }
}

class Product extends Model 
{
    public $incrementing = false;
    protected $casts = [
        'id' => "string"
    ];
}

And as shown in the product relationship of the user I'm using a custom intermediate table model 'App\UserProductPivot':

<?php namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserStationPivot extends Pivot {
    protected $casts = ['product_id' => 'string'];
}

Pivot table migration:

 Schema::create('station_user', function (Blueprint $table) {
    $table->integer('user_id');
    $table->string('product_id');
    $table->boolean('is_primary')->nullable();
    $table->string('label')->nullable();
    $table->integer('sort_order');
    $table->primary(['user_id', 'station_id']);
    $table->timestamps();
});

The problem

Inside a method of the User Model:

$array = [23456 => [
    "is_primary" => true
    "label" => "Test"
    "sort_order" => 1
  ],
  "138seq" => [
    "is_primary" => false
    "label" => "Test"
    "sort_order" => 2
]];
$this->products()->sync($array); 

With the given setup I expected 'product_id' 23456 to be casted to a string but when calling sync() it results in a SQL error on the product_id field as it was not casted to a string.. What is going wrong?



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

Aucun commentaire:

Enregistrer un commentaire