【问题标题】:SQL ordering by field in Zend Framework 2Zend Framework 2 中按字段排序的 SQL
【发布时间】:2013-10-04 10:37:41
【问题描述】:

您将如何(优雅地)使用 Zend Framework 2 中的闭包按字段排序 select 语句?

我有以下 PHP 代码:

$gateway = new \Zend\Db\TableGateway\TableGateway('table_name', $adapter);
$select = $gateway->select(function($select){
    $select->where->in('id', array(4, 2, 3, 1));
    // insert some awesome ordering magic here..!
});

我知道您可以轻松做到这一点:

    ...
    $select->order(array('id ASC'));
    ...

但这只会通过升序id值对结果进行排序,我需要按特定的id序列对它们进行排序(即:让它们按4, 2, 3, 1的序列排序。

我可以在这里使用优雅的 Zend Framework 2 函数来通过id 自己订购吗?有效地创建 SQL:

select * from table_name 
    where 'id' in (4, 2, 3, 1)
    order by field('id', (4, 2, 3, 1));

【问题讨论】:

    标签: php zend-framework2 zend-db zend-db-select


    【解决方案1】:

    这是我发现在 Zend 2 中按字段排序结果的最佳方式。如果您有任何建议/更好的方法,请贡献您自己的解决方案!

    我最终选择了Expression 类来给出想要的结果。举个详细的例子,看看下面的 PHP 代码:

    use Zend\Db\Sql\Expression;
    
    // create the array of ID's we want to order by...
    $ids = array(4, 2, 3, 1);
    
    // get our table gateway and our select going...
    // don't forget the 'use' syntax here...
    $gateway = new \Zend\Db\TableGateway\TableGateway('table_name', $db_adapter);
    $select = $gateway->select(function($select) use($ids){
    
        // standard 'in' functionality...
        $select->where->in('id', $ids);
    
        // use an expression here to achieve what we're looking for...
        $ids_string = implode(',', $ids); // assuming integers here...
        $select->order(array(new Expression('FIELD (id, '. $ids_string .')')));
    
    });
    

    希望这对某人有所帮助!

    【讨论】:

    • 工作就像一个魅力,感谢您发布您的解决方案。在我看来,使用表达式是在 ZF2 中按 FIELD 排序的最佳方式。
    【解决方案2】:

    当您将“优雅”一词应用于函数时,我不确定我是否知道您的意思,但如果是这样的话:

    $select->orderInExactlyThatOrder (array (4,2,3,1));
    

    那么不,我不这么认为。

    【讨论】:

    • 我的意思是使用 Zend 内置功能的意义上的“优雅”,而不是在我的函数中毫无意义地堆积 PHP 代码行,纯粹为了循环结果集和重新排序而进行选择他们效率低下。但是感谢您的回复:)
    猜你喜欢
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多