使用活动记录从多对多中间表获取数据
我在这里发布了完全相同的问题:
through 选项可以在多对多关系中帮助我们什么以及如何帮助我们?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我在这里发布了完全相同的问题:
through 选项可以在多对多关系中帮助我们什么以及如何帮助我们?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
“through”在两个表之间创建关系,这两个表不是通过外键链接,而是通过中间表链接。例如,假设我有 3 个模型:组、用户和评论。关系如下:
组---(hasMany)--->用户----(hasMany)----->评论。
组和评论不是通过外键链接的,但是使用“槽”,它们的行为就好像它们是通过外键链接一样。这当然意味着我们可以在关系查询中享受AR的所有好处。例如,您可以通过以下方式获取属于某个组的用户的所有评论:
在这里您可以找到更详细(但可能更技术一点)的解释: http://www.yiiframework.com/doc/guide/1.1/en/database.arr
只是作为建议,我强烈建议使用 eager在这里加载。解释原因有点大,但如果你使用它,你将避免 AR 执行指数数量的连接查询。
'through' creates a relation between two tables that are not linked by foreign keys, but by a middle table. For instance, let's imagine I have 3 models: Groups, Users, and Comments. The relations would be like this:
Groups---(hasMany)--->Users----(hasMany)----->Comments.
Groups and Comments are not linked by a foreign key, but using 'trough' they will act as if they were. This of course means that we can enjoy all the benefits of AR in relational queries. For example, you could get all the comments of the users who belong to a certain group simply by:
Here you can find a more detailed (but perhaps a bit more technical) explanation: http://www.yiiframework.com/doc/guide/1.1/en/database.arr
Just as an advice, I strongly recommend to use eager loading here. It's a bit large to explain why, but if you use it, you'll avoid AR to perform a exponential number of join queries.