Eduardo
Eduardo

Reputation: 1831

Yii2. Models related

I have 3 models: Items, Serials and SerialsCategories. When I show Item form (to create or update) I need to show the serials which belongs to a categoryId selected in a previous step. A serial can belong to more than one category.

Right now I have on my Item model:

public function getSerialsTypeByCategory() {
        return (new SerialType)->getByCategory($this->itemCategoryId);
    }

On my SerialType model:

public function getByCategory($itemCategoryId) {

        return SerialTypeItemCategory::find()->select(['serialTypeId'])->where(['itemCategoryId' => $itemCategoryId])->all();

    }

This is working, it does what I need but ... Is this the proper way? is there a better way?

Upvotes: 0

Views: 100

Answers (1)

e-frank
e-frank

Reputation: 749

it's not wrong what you are doing. but there is something more - check this link: Working with Relational Data

if you use ->hasOne and ->hasMany to define relations, your model gains some extra benefits, like joining with lazy or eager loading:

Item::findOne($id)->with(['categories'])->all();

with a relation, you can also use ->link and ->unlink, to add/delete related data without having to think about linked fields.

Further, it is easy to define relations via junction table:

class Order extends ActiveRecord
{
    public function getItems()
    {
        return $this->hasMany(Item::className(), ['id' => 'item_id'])
            ->viaTable('order_item', ['order_id' => 'id']);
    }
}

Upvotes: 2

Related Questions