首页 > 代码库 > YII2-数据库数据查询方法,关联查询with, joinWith区别和分页

YII2-数据库数据查询方法,关联查询with, joinWith区别和分页

一、ActiveRecord 活动记录

1.with关联查询

  例如,查询评论

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

 

  等价于以下结果集

 SELECT * FROM `post`;
 SELECT * FROM `comment` WHERE post_id IN (...)
 
 结合Pagination分页查询OK

 

2.joinWith关联查询,返回

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

 等价于:

 SELECT * FROM post LEFT JOIN `comment` comments ON post.`id` = comments.`post_id`;
 SELECT * FROM `comment` WHERE post_id IN (...);
  
 joinWith 返回一个包含关联表的结果集, 可以使用 order by / 过滤条件 / group by 关联数据

  但joinWith 结合Pagination分页查询,只能返回1条记录,为何???

YII2-数据库数据查询方法,关联查询with, joinWith区别和分页