问题描述

haswhere和where不能连用,如果模型后写了haswhere,再写where的话haswhere就没响应了,关于这点,要怎么做才能解决关联时即可以搜索子表的字段又可有搜索本表的字段的查询呢?

场景复现

模型关联搜索部分

$where = new Where();
$tags = DocumentModel::hasWhere('user',['user_type' => '设计师'])->where($where)->with('user')->select();
dump($tags);

tp5.1关于关联模型搜索haswhere和where不能同时使用的问题

如图hasWhere() 根本无效

问题分析和测试

1.单独的haswhere() 查询

$where = new Where();
$tags = DocumentModel::hasWhere('user',['user_type' => '设计师'])->with('user')->select();
dump($tags);

tp5.1关于关联模型搜索haswhere和where不能同时使用的问题

可以看到没有任何问题

2.haswhere() 带空where查询器 查询

$where = new Where();
$tags = DocumentModel::hasWhere('user',['user_type' => '设计师'])->where($where)->with('user')->select();
dump($tags);

tp5.1关于关联模型搜索haswhere和where不能同时使用的问题

可以看到haswhere 直接被忽视了

3.haswhere() 带有条件的where 查询器 查询

$where = new Where();
$where['title'] = ['like','%文档%'];
//由于hasWhere方法使用的是JOIN查询,在查询条件中要指定别名,别名就是模型名
$where['DocumentModel.status'] = 1;
$tags = DocumentModel::hasWhere('user',['user_type' => '设计师'])->where($where)->with('user')->select();
dump($tags);

tp5.1关于关联模型搜索haswhere和where不能同时使用的问题

可以看到 haswhere 再次被忽视了

4.haswhere() 带有条件的where (不用查询器对象) 查询

$tags = DocumentModel::hasWhere('user',['user_type' => '设计师'])->where('title', '文档2')->with('user')->select();
dump($tags);

tp5.1关于关联模型搜索haswhere和where不能同时使用的问题

可以看到这次haswhere 是有效果的

5.单独haswhere() 带有条件的where 查询

$where = new Where();
$where['title'] = ['like','%文档%'];
$tags = DocumentModel::hasWhere('user',$where)->with('user')->select();
dump($tags);

tp5.1关于关联模型搜索haswhere和where不能同时使用的问题

这种也是可以的

总结

haswhere 和 where 一起使用有以下几点要注意

  1. 不能使用where 查询器 ,也就是new Where()这种构造的查询器
  2. where的查询条件和 order 排序字段 组好都要带上别名(也就是模型名)
  3. haswhere 单独使用的话 带有条件where 查询器可以用的

相关文章:

  • 2021-12-24
  • 2021-12-25
  • 2021-07-11
  • 2022-02-02
  • 2022-03-01
  • 2022-01-05
  • 2021-11-23
  • 2021-06-26
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-24
  • 2021-12-13
  • 2021-06-16
相关资源
相似解决方案