vendredi 20 septembre 2019

Broken many-to-many Eloquent relationship with extended model

I have a model Asset with documents() { $this->hasMany(Document::class); } through a table data_asset_document. I extend Asset into multiple models, one of which is Equipment. In my seeder for Equipment, I attempt to create a Document bound to the Equipment record:

$asset = Equipment::create([...]);

$document = Document::create([
    'name' => "$type Purchase Order",
    'tracking_number' => app('incrementer')->current()
]);

$asset->documents()->save($document);

Eloquent produces this query:

update `data_document` set `equipment_id` = 1, `data_document`.`updated_at` = 2019-09-20 14:39:48 where `id` = 1

This is obviously incorrect, since data_document does not have an equipment_id column (Documents "belong to" several models besides Asset). How do I rewrite Asset::documents so that produces the correct mapping, even in its extensions? Or do I need to save my Document through a means other than Asset::documents?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire