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 查詢器可以用的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM