【问题标题】:Laravel 3 / Eloquent ORM : Models extending other modelsLaravel 3 / Eloquent ORM:模型扩展其他模型
【发布时间】:2013-07-02 15:25:24
【问题描述】:

我正在 Laravel 3 中编写一个简单的应用程序,我有 2 个模型:Item 和 PeculiarItem。

PeculiarItem 应该通过简单地添加其他字段(例如“颜色”、“价格”等)来“扩展”项目。

我的想法是,我可以将“核心”类 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. 

}

问题来自在我的 PeculiarItem 对象上调用 save() 方法时 ORM 的硬连线方式。

// ...

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 请求:item/create/peculiaritem

数据:page_id = 1,collection_id = 1,title = 'Foo',...

这会失败,因为 PeculiarItem 没有字段 page_id 或 collection_id。

我该如何解决这种情况? 原则上这是一个坏主意吗?

【问题讨论】:

    标签: php orm laravel eloquent laravel-3


    【解决方案1】:

    您不能也不应该这样做,因为peculiar_items 是它自己的表。

    话虽如此,在您的 Eloquent 模型中,您可以使用 ->has_one->has_many->belongs_to 方法设置关系。然后,您就可以使用Item::find()->peculiar_item()->first()->someSpecialProperty 等...(未经测试)。

    因为我一直在使用 L4,所以我很难记住 L3 的设置 - 他们使用蛇盒。看看这个:http://three.laravel.com/docs/database/eloquent#relationships

    【讨论】:

    • 想象一下,如果我有 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 类。
    • 当你调用模型方法时,Eloquent 仍然会为你做这件事。如果我们错了,我们真的必须看到一个真实的案例。
    • 谢谢,虽然您的 cmets 并没有确切地提出解决方案,但他们实际上帮助我了解了我的方法中的问题:我将为每种“项目”创建一个模型并让他们扩展通用抽象类 Item,但数据库结构仍然是 un-DRY(这意味着我将不得不在那里重复公共字段)。我知道这听起来有点难看,但在我的用例中,我认为这是最有意义的。
    猜你喜欢
    • 2021-07-21
    • 2020-06-19
    • 2015-03-25
    • 1970-01-01
    • 2019-05-21
    • 2013-05-10
    • 1970-01-01
    • 2014-08-23
    • 2023-03-03
    相关资源
    最近更新 更多