是否有类似“has_one :through (from Rails)”的内容?在 Yii 框架中?
我有下表:
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 中也可能吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 Yii 1.1.7 开始(我相信),关系活动记录中现在存在“通过”支持。
http://www.yiiframework.com /doc/guide/1.1/en/database.arr#relational-query-with-through
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
您必须使用“关系”功能来完成类似的事情。最好的介绍页面是关于 ActiveRecord 的页面,您可以在其中找到 在这里。
由于汽车之间的关系是一对多,因此类型为“HAS_MANY”。
例如(假设您有一个汽车和一个制造商模型):
汽车:
制造商:
然后您可以通过以下方式获取制造商的汽车数组:
对于汽车:
这假设两个表都有制造商 ID 字段。
希望有帮助:)
编辑:您没有义务在两个模型中定义关系。例如,如果您不需要汽车制造商,那么完全可以不在那里定义关系函数。
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:
Manufacturer:
You can then fetch an array of cars for a manufacturer through:
For a car:
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.