How to use JOIN in Yii2 Active Record for relational model?(如何在 Yii2 Active Record 中将 JOIN 用于关系模型?)
问题描述
我有 2 个表,名为 Books 和 Reviews.Books 表与 Reviews 是一对多的关系.
我想搜索书籍并按评论对它们进行排序.
例如,如果有 10 本书可用并且书在 Reviews 中有评论,那么我想使用 WHERE 子句查找所有书籍并计算那里的评论,然后根据评论编号对所有书籍进行排序.
我的 SQL 查询如下:
Books::find()->哪里(['和',['like', 'books.bookName', $bookName],['like', 'books.status', 'Enabled']])->joinWith(['reviews' => function ($q){$q->select(['COUNT(*) as cnt']);}])-> orderBy(['cnt' => 'DESC'])-> 全部();
它给了我以下错误消息:
<块引用>SQLSTATE[42S22]:未找到列:1054 'order 子句'中的未知列 'cnt'
我在这里遗漏了什么?
使用 joinWith
.更多见>
例如,对于这样的案例代码:
书籍::find()->joinWith(['reviews' => function ($q) {$q->select(['COUNT(*) as cnt']);}])-> orderBy(['cnt' => 'DESC'])-> 全部();
我找到了更好的解决方案.
书籍::find()->joinWith(['评论'])->select(['*', 'COUNT(reviews.*) as cnt'])->groupBy('RELATION_FIELD(例如:reviews.book_id)')-> orderBy(['cnt' => 'DESC'])-> 全部();
I have 2 tables called Books and Reviews. Books table has a one-to-many relationship with Reviews.
I want to search books and sort them by Reviews.
For example, if there are 10 books available and books has review in Reviews then I want to find all books by using WHERE clause and count there reviews and then order all books based on the review number.
My SQL query is like following:
Books::find()
->where([
'and',
['like', 'books.bookName', $bookName],
['like', 'books.status', 'Enabled']
])
->joinWith(['reviews' => function ($q){
$q->select(['COUNT(*) as cnt']);
}])
->orderBy(['cnt' => 'DESC'])
->all();
It's giving me following error message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cnt' in 'order clause'
What am I missing here?
Use joinWith
. For more see
For example, for your case code like that:
Books::find()
->joinWith(['reviews' => function ($q) {
$q->select(['COUNT(*) as cnt']);
}])
->orderBy(['cnt' => 'DESC'])
->all();
EDIT: I find better solution.
Books::find()
->joinWith(['reviews'])
->select(['*', 'COUNT(reviews.*) as cnt'])
->groupBy('RELATION_FIELD(Example: reviews.book_id)')
->orderBy(['cnt' => 'DESC'])
->all();
这篇关于如何在 Yii2 Active Record 中将 JOIN 用于关系模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Yii2 Active Record 中将 JOIN 用于关系模型?
基础教程推荐
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01