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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里