Doctrine\MongoDB\Query\Expr::sort PHP Method

sort() public method

If sorting by multiple fields, the first argument should be an array of field name (key) and order (value) pairs. This is useful in conjunction with {@link Expr::each()} for a {@link Expr::push()} operation. {@link Builder::sort()} should be used to sort the results of a query.
See also: http://docs.mongodb.org/manual/reference/operator/sort/
public sort ( array | string $fieldName, integer | string $order = null )
$fieldName array | string Field name or array of field/order pairs
$order integer | string Field order (if one field is specified)
    public function sort($fieldName, $order = null)
    {
        $fields = is_array($fieldName) ? $fieldName : [$fieldName => $order];
        foreach ($fields as $fieldName => $order) {
            if (is_string($order)) {
                $order = strtolower($order) === 'asc' ? 1 : -1;
            }
            $sort[$fieldName] = (int) $order;
        }
        return $this->operator('$sort', $sort);
    }

Usage Example

コード例 #1
0
ファイル: ExprTest.php プロジェクト: im286er/ent
 public function testPushWithExpressionShouldEnsureEachOperatorAppearsFirst()
 {
     $expr = new Expr();
     $innerExpr = new Expr();
     $innerExpr->sort('x', 1)->slice(-2)->each(array(array('x' => 1), array('x' => 2)));
     $expectedNewObj = array('$push' => array('a' => array('$each' => array(array('x' => 1), array('x' => 2)), '$sort' => array('x' => 1), '$slice' => -2)));
     $this->assertSame($expr, $expr->field('a')->push($innerExpr));
     $this->assertSame($expectedNewObj, $expr->getNewObj());
 }