ThinkPHP6的关联查询
Mr.Cookie Lv1

ThinkPHP6在处理关联查询的时候(TP8未知),有几个在官方手册没有提到的问题,分为两种情况

一对一/一对多关联

我有一个StoreInventoryModel关联了InventoryModel,我想在查询的时候模糊筛选InventoryModel->inventory_name或者筛选StoreInventoryModel->id

  • 模型
1
2
3
4
5
class StoreInventoryModel extends Model{
public function ingredientInfo(){
return $this->hasOne(IngredientModel::class,'id','ingredient_id');
}
}
  • 查询语句
    1. 主模型必须要有别名或者主模型查询要加上模型的Class名

      • 主模型名
        1
        2
        3
        4
        5
        6
        $query = StoreInventoryModel::with(['ingredient_info']);
        if($keyword = request()->param['keyword']){
        $query->hasWhere('ingredientInfo', [['ingredient_name', 'like', '%' . $keyword . '%']]);
        $query->whereOr('StoreInventoryModel.id','=',$keyword);
        }
        $collections = $query->where('store_id',$store_id)->select();
      • 别名
        1
        2
        3
        4
        5
        6
        $query = StoreInventoryModel::with(['ingredient_info'])->alias('store_inventory')
        if($keyword = request()->param['keyword']){
        $query->hasWhere('ingredientInfo', [['ingredient_name', 'like', '%' . $keyword . '%']]);
        $query->whereOr('store_inventory.id','=',$keyword);
        }
        $collections = $query->where('store_id',$store_id)->select();
    2. hasWhere必须放在前面才会生效

远程关联

在远程关联的时候,因为默认的远程关联生成的join查询语句默认会使用模型名生成的驼峰表名关联中间表,所以这时会alias或者 使用模型名做前缀都会提示找不到列,这时可以在主模型加上alias(‘转换后的小驼峰类名’)来间接的修复这个错误

  • 模型
1
2
3
4
5
6
7
8
9
10
class StoreInventoryCheckModel extends Model{
public function ingredientInfo(){
return $this->hasOneThrough(
IngredientModel::class,
StoreInventoryModel::class,
'id',
'id',
'store_inventory_id',
'ingredient_id',
);
  • 查询语句
1
2
3
4
5
6
$query = StoreInventoryCheckModel::with(['ingredient_info'])->alias('store_inventory_check_model')
if($keyword = request()->param['keyword']){
$query->hasWhere('ingredientInfo', [['ingredient_name', 'like', '%' . $keyword . '%']]);
$query->whereOr('store_inventory_check_model.id','=',$keyword);
}
$collections = $query->where('store_id',$store_id)->select();