使用活动记录从多对多中间表获取数据

发布于 2024-12-23 13:13:09 字数 344 浏览 1 评论 0 原文

我在这里发布了完全相同的问题:

http://www.yiiframework.com/forum/index.php?/topic/25763-grab-data-from-many-to-many-middle-table-using-through/

through 选项可以在多对多关系中帮助我们什么以及如何帮助我们?

I have exactly the same question posted here:

http://www.yiiframework.com/forum/index.php?/topic/25763-grab-data-from-many-to-many-middle-table-using-through/

What and how can the through option help us in a Many-to-Many relation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋凉 2024-12-30 13:13:09

“through”在两个表之间创建关系,这两个表不是通过外键链接,而是通过中间表链接。例如,假设我有 3 个模型:组、用户和评论。关系如下:

组---(hasMany)--->用户----(hasMany)----->评论。

组和评论不是通过外键链接的,但是使用“槽”,它们的行为就好像它们是通过外键链接一样。这当然意味着我们可以在关系查询中享受AR的所有好处。例如,您可以通过以下方式获取属于某个组的用户的所有评论:

$group->comments;

在这里您可以找到更详细(但可能更技术一点)的解释: 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:

$group->comments;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文