开发者

Is there something like "has_one :through (from Rails)" in Yii Framework?

I had the following tables:

manufacturers
* id
* name
* description

types
* id
* name
* description
* manufacturer_id

cars
* id
* title
* description
* type_id

Now my problem is, I want to list the cars with types and manufacurers, e.g:

* Some Car, Fiat Punto
* Another Car, Ferrari F1

...

In rails i can开发者_开发知识库 set the manufacturer relation with sth. like this:

class Car < ActiveRecord::Base
  belongs_to :type
  has_one :manufacturer, :through => :type
end

Is this also possible in Yii?


As of Yii 1.1.7 (I believe), 'through' support exists in relational active record now. http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through


You have to use the "relations" function to accomplish things like that. The best page to get introduced would be the one about the ActiveRecord which you can find here.

Since the relationship between Cars is a one to many the type would be "HAS_MANY".

For example (assuming you have a Car and a Manufacturer model):

Car:

public function relations()
{
   return array('manufacturer' => array(self::BELONGS_TO, 'Manufacturer', 'manufacturerId'));
}

Manufacturer:

public function relations()
{
   return array('cars' => array(self::HAS_MANY, 'Car', 'manufacturerId'));
}

You can then fetch an array of cars for a manufacturer through:

foreach($oManufacturer->cars as $oManufacturer)
   echo $oManufacturer->name;

For a car:

    echo $oCar->manufacturer->name;

This assumes that both tables have the manufacturerId fied. Hope that helps :)

edit: You are not obligated to define the relation in both models. If for example you don't need a manufacturer from a car then it's perfectly okay to not define the relations function there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜