I
I
Ivan2014-03-30 15:14:25
Yii
Ivan, 2014-03-30 15:14:25

What is the correct way to write a relation in a Yii model?

There are two models: Product and ProductPhoto.
The ProductPhoto model has a sort_order attribute (sort order). It is necessary that the first photo (with the lowest sort_order) be available for the request $product->primaryPhoto .
Have I written the relation correctly in the Product model, or is there a more elegant way?

public function relations() {
  return array(
    'photos' => array(self::HAS_MANY, 'ProductPhoto', 'id'),
    'primaryPhoto' => array(self::HAS_ONE, 'ProductPhoto', 'product_id', 'order' => 'sort_order', 'limit' => '1'),
  );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Morozov, 2014-03-30
@0neS

You need to check two things:
1. How it will behave in case of displaying a list of products with a picture (something tells me that a surprise awaits you here)
2. Does HAS_ONE add a default limit (something tells me that yes )
As for the more elegant - I personally have always felt sorry for wasting database time on such things, so the specific implementation is highly dependent on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question