Вопрос

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?

Это было полезно?

Решение

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top