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

后端 未结 3 1161
孤街浪徒
孤街浪徒 2021-01-03 17:59

In the API documentation it is specified that

  • $joinWith - A list of relations that this query should be joined
3条回答
  •  悲哀的现实
    2021-01-03 18:42

    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 = ...
    

    ... 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`;
    

    So 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 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)

提交回复
热议问题