多态模型仅适用于一种模型

时间:2021-03-04 18:53:12

标签: laravel

我目前使用这样的模型建立多态关系:

模型名为 Productable 在我的模型中:

public function productable()
{
  return $this->morphTo();
}

我有另一个名为 Product 的模型,它可以像这样访问 Productable 模型:

public function productDetails()
{
  return $this->morphMany(Productable::class, 'productable');
}

这按预期工作,我可以像这样在 Productable 表中创建记录:

  $p = new Product;
  $p->product_name = $request->product_name;
  $p->product_type = $request->product_type;
  $p->category_id = $request->product_category;
  $p->description = $request->product_description;

  $p->save();

  $p->productDetails()->create([
    'product_id' => $p->id,
  ]);

但是问题是我有另一个模型叫做 Media 其中还有:

公共函数productDetails() { 返回 $this->morphMany(Productable::class, 'productable'); }

在那个模型上,我尝试像这样写一个记录:

              $pMedia = new Media;
              $pMedia->productDetails()->create([
                'product_id' => $p->id,
                'productable_id' => $value,
              ]);

我得到的错误是:

Integrity constraint violation: 1048 Column 'productable_id' cannot be null (SQL: insert into `productables` (`product_id`, `productable_id`, `productable_type`, `updated_at`, `created_at`) values (38, ?, App\Models\Media, 2021-03-04 18:46:51, 2021-03-04 18:46:51))

我在这里做错了什么?我不应该以同样的方式写信给媒体吗?我想知道我错过了什么。

0 个答案:

没有答案