php - Laravel 8 - 使用多态关系时无法设置 morphOne id
问题描述
我使用Polymorphic Relationships
Laravel 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
时间。但是当我创建Cost
并CostItem
喜欢以下内容时:
$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))
我该如何解决这个问题?还是我写错了什么?任何帮助表示赞赏。谢谢。
解决方案
在您问题的以下代码片段中,$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,
]);
推荐阅读
- javascript - 如何让我的函数上限(x)在命令提示符下生成一个数字?
- javascript - 为什么在尝试搜索二叉树时出现无限循环?
- javascript - 如何测试调用外部 api 的 redux-saga 的生成器?
- python - 如何对全年的电子表格数据执行每天的功能
- haskell - 第 6 章,练习 7,从第一原理开始的 Haskell
- c++ - 是否可以使用 MSVS2017 C++ 编译器在类中初始化数组而不会出现错误 C2864?
- go - 管理硬编码的导入路径
- android - 如何从 Kotlin 的同一类活动中调用函数?- 如何从自己的类中循环 CountDowntimer
- php - 如何在php mysql中显示某些记录
- mysql - JPA - 如何使 JSON POST 请求中不需要的字段