duanji4449 2013-07-02 15:25
浏览 82
已采纳

Laravel 3 / Eloquent ORM:扩展其他模型的模型

I'm writing a simple app in Laravel 3 and I have 2 models: Item and PeculiarItem.

PeculiarItem should "extend" Item by simply adding additional fields (say, "color", "price", etc.).

The idea is that I can keep the "core" class Item for common stuff (say, "precedence" or "title") and just extend it for different kinds of items each with their own peculiar set of fields.

    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. 

}

The problems comes from the way ORM is hard-wired when calling the save() method on my PeculiarItem objects.

// ...

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();
    }
}

// ...

Example POST request: item/create/peculiaritem

data: page_id = 1, collection_id = 1, title = 'Foo', ...

This fails because PeculiarItem does not have fields page_id or collection_id.

How can I get around this situation? Is it a bad idea in principle?

  • 写回答

1条回答 默认 最新

  • dongxianglun5163 2013-07-02 15:29
    关注

    You cannot and should not do this since peculiar_items is its own table.

    With that said, in your Eloquent models, you setup the relations with ->has_one, ->has_many, and ->belongs_to methods. From there, you would then be able to use Item::find()->peculiar_item()->first()->someSpecialProperty, etc... (untested).

    Since I've been using L4, it's hard for me to remember the setup for L3 - they use snake case. Check this out: http://three.laravel.com/docs/database/eloquent#relationships

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分