I currently have a polymorphic relationship using a model like so:
The model is called Productable
In the model I have:
public function productable()
{
return $this->morphTo();
}
I have another model called Product that has access to the Productable model like so:
public function productDetails()
{
return $this->morphMany(Productable::class, 'productable');
}
This works as expected and I can create a record in the Productable table like so:
$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,
]);
However the issue is I have another model called Media
which also has:
public function productDetails() { return $this->morphMany(Productable::class, 'productable'); }
On that model I attempt to write a record like so:
$pMedia = new Media;
$pMedia->productDetails()->create([
'product_id' => $p->id,
'productable_id' => $value,
]);
The error I get is:
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))
What am I doing wrong here? Shouldn't I be to write to Media in the same way? I'm wondering what I'm missing.