業務背景:
最近在做龍巔廣告系統,使用了新的tp6框架
相關數據結構:
advert_plan 廣告計划表
advert_plan_position 廣告計划位置表
這兩個表示 計划表和位置表是 1:n
需求:
在計划列表中的信息已經是包含跨表信息,其中就有位置表里的信息,那該怎么做呢?
/** * 廣告計划表 * Class AdvertPlan * @package app\common\model * @author:hann * @time:2020-03-10 */ namespace app\common\model; class AdvertPlan extends Common { protected $pk = 'plan_id'; /** * 位置關聯模型 1對n * User: feng * Date: 2020-03-14 * @return \think\model\relation\HasMany */ public function planPosition() { return $this->hasMany(AdvertPlanPosition::class, 'plan_id', 'plan_id'); } }
寫了 在Plan表的model里寫關聯模型planPosition方法
然后執行查詢如下
//連表查詢 $data = $model_plan->with(['planPosition']) ->field('*') ->where($where) ->order('plan_id') ->paginate(); echo $model_plan->getLastSql(); dd($data->toArray());
這樣連表查詢是沒問題的。
但問題來了,根據需求,【要根據位置來篩選計划】,那就得設置位置表的where條件唄,代碼如下:
//連表查詢,異常 //haswhere 關聯表查詢失敗! $data = $model_plan->with(['planPosition']) ->field('*') ->where($where) ->hasWhere('planPosition',['position'=>1]) ->order('plan_id') ->paginate(); echo $model_plan->getLastSql(); dd($data->toArray());
問題來了,提示報錯:
#0 [10501]PDOException in PDOConnection.php line 722 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'AdvertPlan.plan_id' in 'on clause'
錯誤原因:
with不能與hasWhere連用,必須使用with閉包的形式才能實現子模型的條件篩選,具體如下:
//連表查詢 $data = $model_plan->with( [ 'planPosition' => function($query) { if(!empty($where_position)){ $query->where($where_position); } }, ]) ->field('*') ->where($where) ->order('plan_id') ->paginate(); echo $model_plan->getLastSql(); dd($data->toArray());
author:hann
手冊鏈接:https://www.kancloud.cn/manual/thinkphp6_0/1037600