douchong4730 2010-06-30 19:01
浏览 118
已采纳

如何在ORM查询中混合使用OR和AND

I am developing a site using kohana 2.3 and am having trouble with a specific ORM query. Essentially what I am doing is the following query

SELECT *
   FROM 'records'
   WHERE ('ServRepSupervisor' = name AND 'Followup_read' = 0) OR ('ServRepSupervisor' = name AND `read` = 0)

when I try the ORM query like this...

$unread = ORM::factory('record')
   ->where(array('ServRepSupervisor' => Auth::instance()->get_user()->name, 'Followup_read' => 0))
   ->orwhere(array('ServRepSupervisor' => Auth::instance()->get_user()->name, 'read' => 0))
   ->find_all();

the query i end up with is

SELECT `records`.*
   FROM (`records`)
   WHERE `ServRepSupervisor` = 'name' AND `Followup_read` = 0
   OR `ServRepSupervisor` = 'name'
   OR `read` = 0

How can I rework that ORM query to produce the intended result?

EDIT: I managed to get it to work but it does not seem like a very elegant solution.

$unread = ORM::factory('record')
   ->where('(\'ServRepSupervisor\' = \'' . Auth::instance()->get_user()->name . '\' AND \'Followup_read\' = 0) OR (\'ServRepSupervisor\' = \'' . Auth::instance()->get_user()->name . '\' AND \'read\' = 0)')
   ->find_all();

This returns the dataset I want but it's just ugly code. There must be a better way of doing this.

  • 写回答

3条回答 默认 最新

  • 普通网友 2010-07-02 13:30
    关注

    Well after a bit of research, I have found a patch for altering KO2 ORM to have open_paren() and close_paren() but the default behavior of orwhere in KO2 does not allow the desired operation so the parens will not help me. I have resigned myself to the fact that the detailed where() method that I am using is the best option for me given my time constraints. I have altered the query slightly to accommodate some peculiarities in my mysql instance.

    This works and is the final query for this project.

    $unread = ORM::factory('record')
       ->where('(ServRepSupervisor = \'' . Auth::instance()->get_user()->name . '\' AND Followup_read = 0) OR (ServRepSupervisor = \'' . Auth::instance()->get_user()->name . '\' AND records.read = 0)')
       ->find_all();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket