首页 > 解决方案 > Laravel 8 - 使用多态关系时无法设置 morphOne id

问题描述

我使用Polymorphic RelationshipsLaravel 8 声明Models如下:

Item

class Item extends Model
{
    protected $table = 'items';
    
    public function costs()
    {
        return $this->belongsToMany(Receive::class, 'cost_item', 'cost_id', 'item_id')
            ->withPivot([
                'id',
                'cost_id',
                'item_id',             
                'sku_id',
                'qty',              
                'price',
            ])
            ->withTimestamps()
            ->using(CostItem::class);
    }
}

Movement

class Movement extends Model
{
    protected $table = 'movements';
    
    public function movable()
    {
        return $this->morphTo();
    }
}

Cost

class Cost extends Model
{
    protected $table = 'costs';
    
    public function items()
    {
        return $this->belongsToMany(Item::class, 'cost_item', 'cost_id', 'item_id')
            ->withPivot([
                'id',
                'cost_id',
                'item_id',             
                'sku_id',
                'qty',              
                'price',
            ])
            ->withTimestamps()
            ->using(CostItem::class);
    }
}

CostItem

class CostItem extends Pivot
{
    protected $table = 'cost_item';
    
    public function movement()
    {
        return $this->morphOne(Movement::class, 'movable');
    }
    
    public function syncMovement()
    {
        $this->movement()->updateOrCreate([], [
            'sku_id' => $this->sku_id,
            'qty' => $this->qty,
            'price' => $this->cost, 
        ]);
    }
    
    protected static function booted()
    {
        static::created(function ($model) {
            $model->syncMovement();
        });
    }
}

我使用中的created事件CostItem,我想将CostItem数据同步到Movement创建CostItem时间。但是当我创建CostCostItem喜欢以下内容时:

$cost = new Cost;
$cost->number = 'A00001';
$cost->note = 'test';
$cost->save();

$cost->items()->attach($item, [
    'sku_id' => 1,
    'qty' => 10,
    'price' => 100,
]);

我总是得到错误:

Next Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'movable_id' cannot be null (SQL: insert into `movements` (`movable_id`, `movable_type`, `sku_id`, `quantity`, `price`, `remaining`, `updated_at`, `created_at`) values (?, App\Models\ReceiveItem, 1, ?, 100, ?, 2020-12-01 10:27:03, 2020-12-01 10:27:03)) 

我该如何解决这个问题?还是我写错了什么?任何帮助表示赞赏。谢谢。

标签: phplaraveleloquentlaravel-8

解决方案


在您问题的以下代码片段中,$cost = new Cost是一个新实例,它不代表数据库中的现有记录,因此它没有 id value id=null

因此,当您尝试通过关系更新或创建相关记录时,它会报错。

由于它没有 id,因此通过关系创建相关记录的任何调用都将失败。

从数据库中获取 $cost 的新记录,然后通过关系调用更新或创建相关记录。

$cost = new Cost;
$cost->number = 'A00001';
$cost->note = 'test';
$cost->save();

$cost->fresh()->items()->attach($item, [
    'sku_id' => 1,
    'qty' => 10,
    'price' => 100,
]);

推荐阅读