【问题标题】:Is it possible to run findFirst() with IN clause in Phalcon?是否可以在 Phalcon 中使用 IN 子句运行 findFirst()?
【发布时间】:2016-07-20 19:04:14
【问题描述】:

我想在findFirst 中使用IN 子句,但它似乎不起作用?

预期的代码,或类似的东西:

$item = Item::findFirst([
    'conditions' => 'categories IN :cats: AND released < :now:',
    'order'      => 'id ASC',
    'bind'       => [
        'cats'     => $this->categories,
        'released' => time()
    ],
]);

我尝试使用 bindTypes,但没有这样的“列表”或“数组”类型(而且,这会比预期的更冗长)...

我知道我可以通过查询生成器做到这一点,但我希望让它更惯用:

$item = Item::query()
    ->inWhere('categories', $this->categories)
    ->andWhere('released < :now:', ['now' => time()])
    ->orderBy('id ASC')
    ->limit(1)
    ->execute()
    ->getFirst();

【问题讨论】:

    标签: phalcon phalcon-orm


    【解决方案1】:

    你可以像这样绑定数组和IN子句:

    $result = ModelName::findFirst([
        'conditions' => 'id in ({cats:array})',
        'bind' => array('cats' => [3, 5, 8])
    ]);
    

    请注意,上面的示例将获得 id 为 3 的第一条记录。但是,如果您使用 find(),您将获得 3、5 和 8 的项目。

    docs 中的更多示例(在本节的底部)。

    【讨论】:

    • 检查我的链接。它在我上面给你的链接的第三个代码块中。
    • 我敢打赌它一定是新的东西。去年我一直在寻找这样的解决方案两次,但以前从未见过。看起来它也适用于字符串!
    • 此 PHQL 占位符自 2015 年 7 月起可用 - github.com/phalcon/cphalcon/releases/tag/phalcon-v2.0.4
    猜你喜欢
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    相关资源
    最近更新 更多