我在Laravel 3中編寫了一個簡單的應用程序,並且我有2個模型:Item和PeculiarItem。Laravel 3/Eloquent ORM:擴展其他模型的模型
PeculiarItem應該通過簡單地添加額外的字段(比如「color」,「price」等)來「擴展」Item。
這個想法是,我可以爲常見的東西(比如說「優先」或「標題」)保留「核心」類項目,並將其擴展爲各自具有各自獨特字段的各種項目。
class Item extends Eloquent
{
// Just a simple model with a couple relationship with other models, such as Page, Collection
public static $table = 'items';
public function page()
{
return $this->belongs_to('Page');
}
public function collection()
{
return $this->belongs_to('Collection');
}
}
// ...
class PeculiarItem extends Item
{
public static $table = 'peculiar_items';
// Ideally this PeculiarItem needn't redeclare the page_id and collection_id foreign key fields
// because it extends Item.
}
這個問題來自於ORM在調用我的PeculiarItem對象上的save()方法時硬連線的方式。
// ...
class Item_Controller extends Base_Controller
{
/**
* @param $type the class name of the object we are creating
* @param $data the data for the new object
* @return mixed
*/
public function action_create($type = null, $data = null)
{
// ... filter, validate data, etc.
$entry = new $type($data);
$entry->save();
}
}
// ...
例POST請求:項目/創建/ peculiaritem
數據:PAGE_ID = 1,collection_id = 1,標題= '富',...
失敗的原因PeculiarItem不具有字段page_id或collection_id。
我該如何解決這種情況? 原則上這是一個壞主意嗎?
想象一下,如果我有15個不同的類擴展Item。那麼我是否應該創建15種不同的方式來處理Item_Controller中的對象創建呢? –
沒關係。雄辯是聰明的。你可以'Item :: find(123) - > peculiar_items() - > get()' - 這將返回與父項目相關的所有特有項目。這種關係可以在你的'Item'模型中設置,方法'peculiar_items(){return $ this-> has_many('peculiar_items','parent_key_name'); }' –
在閱讀我的問題後,我可能已經意識到情況不夠清楚,所以這裏是另一個嘗試。 如果你想創建一個API,讓你添加幾種物品,但保持模型/表格乾燥,該怎麼辦?想象一下,所有項目都具有某些共同特徵(優先級,標題等),但每種項目都有其特定的功能(顏色/重量,任何可能的組合)。我的目標是創建一個類似於「create/item」的API調用,以便一次獲取所有數據並實例化正確類型的Item類。 –