Home  >  Q&A  >  body text

php - Yii relational table with optimized query to avoid N+1 query questions

Example: A certain post details page
Details page hasMany associationComment table
Comment table hasOne associationUser table
User table hasOne associationUser data table

Then for the comment list, you can query the user table through with('author') association, avoiding N 1 queries

But at this time, through user tableassociation queryuser data table, it is still N 1 queries.

How to associate the user table and user data table through with in one go?

阿神阿神2666 days ago1092

reply all(2)I'll reply

  • 欧阳克

    欧阳克2017-06-10 09:49:45

    Comment associated user: getAuthor
    User associated user data: getAuthorname
    Can be retrieved with ('author.authorname').
    If you want to see an example, this video chapter just talks about retrieving data from multi-layer associations.

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-10 09:49:45

    I haven’t used yii2 for a long time. When I used ActiveRecord, I would directly write SQL to handle complex statements. I was too lazy to change the model file here and there. Use native SQL, as long as you think the performance is fine. , LEFT JOIN association is enough, use findBySQL() to check.

    reply
    0
  • Cancelreply