php Yii2 中的 $with 和 $joinWith 有什么区别以及何时使用它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25600048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:54:38  来源:igfitidea点击:

What is the difference between $with and $joinWith in Yii2 and when to use them?

phpyiiyii2

提问by NAT3863

In the API documentation it is specified that

在 API 文档中指定

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

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

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

采纳答案by lin

Difference between withand joinWith

with和之间的区别joinWith

Using withmethod results the following SQL queries

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

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

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

... while using joinWithwill result in this SQL query

...而使用joinWith将导致此 SQL 查询

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

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

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

所以joinWith我在需要过滤或搜索相关表中的数据时使用。

Additional informations

附加信息

The docu-> http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#joining-with-relationswill tell you this:

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

"When working with relational databases, a common task is to join multiple tables and apply various query conditions and parameters to the JOIN SQL statement. Instead of calling yii\db\ActiveQuery::join() explicitly to build up the JOIN query, you may reuse the existing relation definitions and call yii\db\ActiveQuery::joinWith() to achieve this goal."

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

Which means, you are able to handle joins, innerJoins, outerJoinsand all the good related stuff in Yii2 by yourself now. Yii (not Yii2) only uses joininstead 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)

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

回答by topher

joinWithuses JOINto include the relations in the original query while withdoes not.

joinWith用于JOIN在原始查询中包含关系,而with没有。

To illustrate further, consider a class Postwith a relation commentsas follows:

为了进一步说明,考虑一个Post具有comments如下关系的类:

class Post extends \yii\db\ActiveRecord {
    ...
    public function getComments() {
        return $this->hasMany(Comment::className(), ['post_id' => 'id']);
    }
}

Using withthe code below:

使用with以下代码:

$post = Post::find()->with('comments');

results in the following sql queries:

导致以下 sql 查询:

SELECT `post`.* FROM `post`;
SELECT `comment`.* FROM `comment` WHERE post_id IN (...)

Whereas the joinWithcode below:

joinWith下面的代码:

$post = Post::find()->joinWith('comments', true)

results in the queries:

结果查询:

SELECT `post`.* FROM post LEFT JOIN `comment` comments ON post.`id` = comments.`post_id`;
SELECT `comment`.* FROM `comment` WHERE post_id IN (...);

As a result, when using joinWithyou may order by/filter/group by the relation. You may have to disambiguate the column names yourself.

因此,在使用时,joinWith您可以按关系排序/过滤/分组。您可能必须自己消除列名称的歧义。

Reference: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#lazy-eager-loading

参考:http: //www.yiiframework.com/doc-2.0/guide-db-active-record.html#lazy-eager-loading

回答by Dhiraj Gupta

Please note that in addition to above awesome answers that helped me figure out how to use joinWith(), that whenever you want to use joinWith()and you have ambiguous column names, Yii / ActiveRecord automagically seems to pick a random column, instead of what you're usually expecting (the leftmost table). It is best to specify the leftmost table in the SELECTclause, by specifying something like $query->select("post.*"). I was getting ids from some inner tables and they were getting used like they werefrom the leftmost table, until I figured this out.

请注意,除了上面帮助我弄清楚如何使用的很棒的答案之外joinWith(),每当您想使用joinWith()并且列名不明确时,Yii / ActiveRecord 似乎会自动选择一个随机列,而不是您通常期望的列(最左边的表)。最好SELECT通过指定类似的内容来指定子句中最左边的表$query->select("post.*")。我从一些内部表中获取 id,并且它们像从最左边的表中一样使用,直到我想通了这一点。

Another point to note is that you canspecify an an alias for the joinwith relation, so you could say something like:

另一点要注意的是,您可以为 joinwith 关系指定一个别名,因此您可以这样说:

$post->find()
->joinWith(["user u"])
->where(["u.id"=>$requestedUser->id])
->select("post.*")
->orderBy(["u.created_at"=>SORT_DESC]);