Yii2 中的 $with 和 $joinWith 有什么区别以及何时使用它们? [英] What is the difference between $with and $joinWith in Yii2 and when to use them?

查看:35
本文介绍了Yii2 中的 $with 和 $joinWith 有什么区别以及何时使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 API 文档中指定

In the API documentation it is specified that

  • $joinWith - 此查询应该加入
  • 的关系列表
  • $with - 此查询应该执行的关系列表
  • $joinWith - A list of relations that this query should be joined with
  • $with - A list of relations that this query should be performed with

这些ActiveQuery属性有什么区别,在什么情况下我们应该使用$joinWith$with?

What is the difference between these ActiveQuery property and under what situation should we use $joinWith and $with?

推荐答案

withjoinWith

的区别

使用 with 方法产生以下 SQL 查询

Difference between with and joinWith

Using with method results the following SQL queries

$users = User::find()->with('userGroup');

SELECT * FROM `user`;
SELECT * FROM `userGroup` WHERE userId = ...

...同时使用 joinWith 将导致此 SQL 查询

... while using joinWithwill result in this SQL query

$users = User::find()->joinWith('userGroup', true)

SELECT * FROM user LEFT JOIN `userGroup` userGroup ON user.`id` = userGroup.`userId`;

所以当我需要过滤或搜索相关表中的数据时,我使用了 joinWith.

So I'am using joinWith when I need to filter or search data in the related tables.

docu-> http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#joining-with-relations 会告诉你:

"在使用关系型数据库时,一个常见的任务是连接多个表,并在 JOIN SQL 语句中应用各种查询条件和参数.而不是显式调用 yii\db\ActiveQuery::join() 来构建在 JOIN 查询中,您可以重用现有的关系定义并调用 yii\db\ActiveQuery::joinWith() 来实现此目标."

这意味着,您现在可以自己处理 joinsinnerJoinsouterJoins 以及 Yii2 中所有相关的好东西.Yii(不是 Yii2)只使用 join 而不是让用户决定 join 的类型.关于Join's"的详细信息 -> 它是一个基于 SQL 的东西.您可以在此处阅读有关内容 http://en.wikipedia.org/wiki/Join_(SQL)

Which means, you are able to handle joins, innerJoins, outerJoins and all the good related stuff in Yii2 by yourself now. Yii (not Yii2) only uses join instead without letting the user decide about type of join. Details about "Join's" -> its a SQL-Based thing. You can read about this here http://en.wikipedia.org/wiki/Join_(SQL)

这篇关于Yii2 中的 $with 和 $joinWith 有什么区别以及何时使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆