【问题标题】:Is there something like "has_one :through (from Rails)" in Yii Framework?Yii 框架中有类似“has_one :through (from Rails)”的东西吗?
【发布时间】:2011-06-18 04:18:00
【问题描述】:

我有以下表格:

manufacturers
* id
* name
* description

types
* id
* name
* description
* manufacturer_id

cars
* id
* title
* description
* type_id

现在我的问题是,我想列出汽车的类型和制造商,例如:

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

...

在rails中我可以设置制造商关系。像这样:

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

这在 Yii 中也可以吗?

【问题讨论】:

    标签: activerecord relationship yii has-many-through


    【解决方案1】:

    从 Yii 1.1.7 开始(我相信),“通过”支持现在存在于关系活动记录中。 http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through

    【讨论】:

      【解决方案2】:

      你必须使用“关系”功能来完成类似的事情。最好的介绍页面是关于 ActiveRecord 的页面,您可以找到 here

      由于 Cars 之间的关系是一对多的,因此类型将是“HAS_MANY”。

      例如(假设您有 Car 和 Manufacturer 型号):

      汽车:

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

      制造商:

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

      然后,您可以通过以下方式为制造商获取一系列汽车:

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

      对于汽车:

          echo $oCar->manufacturer->name;
      

      这假定两个表都具有制造商 ID。 希望有帮助:)

      edit:您没有义务在两个模型中定义关系。例如,如果您不需要汽车制造商,那么不在那里定义关系函数是完全可以的。

      【讨论】:

      • 谢谢。这也是我目前的解决方案(在类型和汽车中插入manufacturer_id)。但是是否可以在汽车表中创建没有manufacturer_id 的关系?
      • 我能看到的唯一其他解决方案是创建一个包含 carId manufacturerId 条目的映射表。这会稍微多一些工作,因为您必须先执行 findByAttributes 来定位汽车或制造商,并将它们链接到实际对象。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 2021-08-04
      • 2012-05-31
      • 2012-11-27
      相关资源
      最近更新 更多