【问题标题】:Kohana 3 ORM - grouping where conditions with parenthesesKohana 3 ORM - 用括号对条件进行分组
【发布时间】:2010-06-12 14:03:42
【问题描述】:

我正在尝试像这样通过 ORM 运行查询:

   SELECT * from table where (fname like 'string%' or lname like 'string%') 
AND (fname like 'string2%' or lname like 'string2%');

这是我目前所拥有的:

$results = ORM::factory('profiles');
foreach ($strings as $string) {
    $result->where('fname', 'like', "$string%");
    $result->or_where('lname', 'like', "$string%");
}

但这并没有考虑括号。有什么想法吗?

【问题讨论】:

标签: php orm kohana kohana-3 kohana-orm


【解决方案1】:

找到答案了。

这是通过 Kohana 的 where_open() 和 where_close() 方法完成的。

【讨论】:

  • 抱歉,DexterW,我无意中否决了你的回答,现在它不会让我撤消否决...
【解决方案2】:

对我来说很好用。

ORM 代码示例

$musicslist = ORM::factory('user_music')
            ->where_open()
            ->where('title', 'like', '%' . $search . '%')
            ->or_where('album', 'like', '%' . $search . '%')
            ->or_where('artist', 'like', '%' . $search . '%')
            ->where_close()
            ->and_where('app_userid','=', $userid)
            ->find_all();

它将创建 SQL 查询

SELECT `user_musics`.* FROM `user_musics` WHERE (`title` LIKE '%as%' OR `album` LIKE '%as%' OR `artist` LIKE '%as%') AND `app_userid` = '21'

【讨论】:

    【解决方案3】:

    无法让代码格式在评论中起作用 - 只是想我会在答案中添加一个简单的示例,以防其他人遇到它:

    $query = DB::select()
               ->from('some_table')
               ->where_open()
               ->where('column_one', '=', 1)
               ->or_where('column_two', '=', 2)
               ->where_close();
    

    将产生以下 SQL:

    SELECT * FROM some_table
    WHERE (column_one = 1 OR column_two = 2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      相关资源
      最近更新 更多