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

后端 未结 3 1247
孤街浪徒
孤街浪徒 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条回答
  •  旧时难觅i
    2021-01-03 18:47

    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 SELECT 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:

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

提交回复
热议问题