In the API documentation it is specified that
$joinWith
- A list of relations that this query should be joined with$with
- A list of relations that this query should be performed with
What is the difference between these ActiveQuery property and under what situation should we use $joinWith
and $with
?
joinWith
usesJOIN
to include the relations in the original query whilewith
does not.To illustrate further, consider a class
Post
with a relationcomments
as follows:Using
with
the code below:results in the following sql queries:
Whereas the
joinWith
code below:results in the queries:
As a result, when using
joinWith
you may order by/filter/group by the relation. You may have to disambiguate the column names yourself.Reference: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#lazy-eager-loading
Difference between
with
andjoinWith
Using
with
method results the following SQL queries... while using
joinWith
will result in this SQL querySo I'am using
joinWith
when I need to filter or search data in the related tables.Additional informations
The docu -> http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#joining-with-relations will tell you this:
"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."
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 usesjoin
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)Please note that in addition to above awesome answers that helped me figure out how to use
joinWith()
, that whenever you want to usejoinWith()
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 theSELECT
clause, by specifying something like$query->select("post.*")
. I was getting ids from some inner tables and they were getting used like they were from the leftmost table, until I figured this out.Another point to note is that you can specify an an alias for the joinwith relation, so you could say something like: