zoukankan      html  css  js  c++  java
  • tp5.1关于关联模型搜索haswhere和where不能同时使用的问题

    问题描述

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

    场景复现

    模型关联搜索部分

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

    image-20200713195954804

    如图hasWhere() 根本无效

    问题分析和测试

    1.单独的haswhere() 查询

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

    image-20200714093825174

    可以看到没有任何问题

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

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

    image-20200714094119366

    可以看到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);
    

    image-20200714100110575

    可以看到 haswhere 再次被忽视了

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

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

    image-20200714100542174

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

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

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

    image-20200721170627491

    这种也是可以的

    总结

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

    1. 不能使用where 查询器 ,也就是new Where()这种构造的查询器
    2. where的查询条件和 order 排序字段 组好都要带上别名(也就是模型名)
    3. haswhere 单独使用的话where 查询器可以用的
  • 相关阅读:
    HDU 4296 Buildings(贪心)
    HDU 4288 Coder(线段树)
    hdu 5073 Galaxy
    ZOJ 3905 Cake(贪心+dp)
    ZOJ 3903 Ant(公式推导)
    除法求逆元(扩展欧几里德和费马小定理)
    HDU 4442 Physical Examination(关于贪心排序)
    ACM vim配置
    2015 南阳ccpc The Battle of Chibi (uestc 1217)
    次小生成树(入门)
  • 原文地址:https://www.cnblogs.com/makalochen/p/13298231.html
Copyright © 2011-2022 走看看