Laravel 5.7:雄辩的Pivot字段未使用sync()进行强制转换

时间:2018-12-06 01:15:18

标签: laravel laravel-5 eloquent

我有以下具有多对多关系的雄辩模型:

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"
    ];
}

并且如用户的产品关系所示,我正在使用自定义的中间表模型'App \ UserProductPivot':

<?php namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

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

数据透视表迁移:

 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', 'product_id']);
    $table->timestamps();
});

问题

用户模型方法内:

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

在给定的设置下,我希望将'product_id'23456强制转换为字符串,但是在调用sync()时,由于未将其强制转换为字符串,因此会在product_id字段上导致SQL错误。这是怎么回事?

0 个答案:

没有答案