一对多的关联统计查询时,指定的localkey问题

浏览:2543 发布日期:2019/06/02 分类:ThinkPHP6专区
<?php

namespace app\common\model;

use think\Model;

class BookCategory extends Model
{

    protected $schema = [
        'category_name' => 'varchar',
        'description' => 'varchar',
        'object_id' => 'varchar',
        'create_time' => 'int',
        'delete_time' => 'int'
    ];

    /**
     * 关联书本信息表模型
     *
     */
    public function books()
    {
        return $this->hasMany(BookInformation::class, 'category_id', 'object_id');
    }

}
关联统计时$category = new BookCategory();
$classify = $category
            ->withCount('books')
            ->fetchSql()
            ->select();

        halt($classify);
生成的sql语句为
SELECT *,(SELECT COUNT(*) AS tp_count FROM `book_information` `count_table` WHERE ( `count_table`.`category_id` = book_category.id )) AS `books_count` FROM `book_category`

在关联方法中,指定了localkey,但生成的sql中依旧是id

于是查看源码,发现一对多中return $this->query->alias($aggregate . '_table')
            ->whereExp($aggregate . '_table.' . $this->foreignKey, '=' . $this->parent->getTable() . '.' . $this->parent->getPk())
            ->fetchSql()
            ->$aggregate($field);
将$this->parent->getPk()改为$this->localKey即解决问题
最佳答案
评论( 相关
后面还有条评论,点击查看>>