問題描述
haswhere和where不能連用,如果模型后寫了haswhere,再寫where的話haswhere就沒響應了,關於這點,要怎么做才能解決關聯時即可以搜索子表的字段又可有搜索本表的字段的查詢呢?
場景復現
模型關聯搜索部分
$where = new Where();
$tags = DocumentModel::hasWhere('user',['user_type' => '設計師'])->where($where)->with('user')->select();
dump($tags);
如圖hasWhere() 根本無效
問題分析和測試
1.單獨的haswhere() 查詢
$where = new Where();
$tags = DocumentModel::hasWhere('user',['user_type' => '設計師'])->with('user')->select();
dump($tags);
可以看到沒有任何問題
2.haswhere() 帶空where查詢器 查詢
$where = new Where();
$tags = DocumentModel::hasWhere('user',['user_type' => '設計師'])->where($where)->with('user')->select();
dump($tags);
可以看到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);
可以看到 haswhere 再次被忽視了
4.haswhere() 帶有條件的where (不用查詢器對象) 查詢
$tags = DocumentModel::hasWhere('user',['user_type' => '設計師'])->where('title', '文檔2')->with('user')->select();
dump($tags);
可以看到這次haswhere 是有效果的
5.單獨haswhere() 帶有條件的where 查詢
$where = new Where();
$where['title'] = ['like','%文檔%'];
$tags = DocumentModel::hasWhere('user',$where)->with('user')->select();
dump($tags);
這種也是可以的
總結
haswhere 和 where 一起使用有以下幾點要注意
- 不能使用where 查詢器 ,也就是new Where()這種構造的查詢器
- where的查詢條件和 order 排序字段 組好都要帶上別名(也就是模型名)
- haswhere 單獨使用的話 帶有條件where 查詢器可以用的