laravel - Eloquent Model with dynamic table..? -
i've got generic model called item
, related model called itemproperties
.
item -> hasone -> itemproperties
itemproperties -> belongsto -> item
the item
model has property called 'itemtype_id' tells model table store to. ex: itemtype = 1, table itemproperties_1 itemtype = 2, table itemproperties_2.
so changed gettable() method on itemproperties model:
function gettable(){ return 'item_properties_' . $this->itemtype_id; }
so, when creating new item , properties, i've been setting itemproperties this:
// create & save item $item = new item(['itemtype_id' => $itemtype_id]); $item->save(); // save properties $itemproperties = new itemproperties($properties); $itemproperties->itemtype_id = $item->itemtype_id; $item->properties()->save($itemproperties);
this seems work fine... when saving itemproperties.
however, when try retrieve them, doing $item->properties
, don't have way tell itemtype_id, can't find correct table.
my question: is there way set eloquent relationship can pass item->itemtype_id itemproperties knows table use?
or there better overall strategy accomplish i'm doing using different tables different item types?
you shouldn't need multiple tables solve this. having relationship between item , properties should sufficient. means in item
model, should specify column use when building relationship property
public function property() { return $this->hasone(property::class, 'itemtype_id', 'itemtype_id') }
this means itemtype_id in items
table, , assumption here itemtype_id in property model unique (one - - one)
then when have save new properties:
$item = new item(['itemtype_id' => $itemtype_id]); $item->save(); //then saving properties $item->property()->save($properties); //assuming have $properties.
the itemtype_id
passed when building query , references. means if want retrieve properties incase find item type id:
$item = item::where('itemtype_id', 1)->first(); //get properties $properties = $item->property; //or properties calling property model directly: property::where('item_property', 1)->first();
the ways might wrong if fields in different properties varies and/or misunderstood question, don't need multiple tables.
Comments
Post a Comment