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 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办