<?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即解决问题 最佳答案