// 伪代码
class Cylinders extends Model
{
public function company()
{
return $this->belongsTo('Company');
}
public function CylindersRecord()
{
return $this->hasMany('CylindersRecord');
}
public function get_cylinders_record_count($param)
{
$name[] = ['name','like','%'.$param['name'].'%'];
$where[] = ['product_number','like','%'.$param['product_number'].'%'];
return $this->hasWhere('company',$name)->withCount('CylindersRecord',false)
->where($where)->field('Cylinders.id,product_number')
->order(array('company_id'=>'desc','Cylinders.id'))->paginate(10);
}
}
#withCount第二个参数false表示不使用子查询
SELECT `Cylinders`.*,
(SELECT
COUNT(*) AS tp_count
FROM
`gu_cylinders_record` `count_table`
WHERE ( `count_table`.`cylinders_id` = gu_cylinders.id )
) AS `cylinders_record_count`,`id`,`product_number`
FROM
`gu_cylinders` `Cylinders`
INNER JOIN `gu_company` `Company` ON `Cylinders`.`company_id` = `Company`.`id`
ORDER BY
`company_id` DESC,
`Cylinders`.`id`
LIMIT 0,10;
1、这是当使用hasWhere时的sql语句,因为关联导致子查询中的 `gu_cylinders` 无法识别所以报错,当不使用子查询时,就不会有这个问题;
2、不使用子查询时,`id`字段会报错,因为找不到所属表,给`id`字段加上表别名`Cylinders`即可
3、模型关联时,表别名默认为类名