Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, how to determine if query builder already contains "order"?

I'm trying to to go a default order if a relationship doesn't already have an order. But if it does I don't use the default.

$q = $this->items();

if (empty($q->orders)) {
    $q = $q->order();
}

Note that order() is just a default method in the a BaseModel class. For some reason when I try to call the orders property on the query builder it says Undefined property even though it's a public property in the Builder class.

Not sure why, or how I can check for this.

EDIT:

I setup a full example in a route:

class Test extends \Illuminate\Database\Eloquent\Model {}

$router->get('/test', function () {
    $test = new Test;
    $q = $test->select('id')->orderBy('id', 'desc');
    $bindings = $q->getRawBindings();
    var_dump($bindings);
    return 'test';
});

The dump just spits out the query builder object rather than the bindings?

like image 499
Rob Avatar asked Aug 11 '15 09:08

Rob


2 Answers

After some toying around, finally got it going.

So actually it's an instance of Eloquent\Builder not Query\Builder so need to do:

$q->getQuery()->orders

This gets you access to the query object.

like image 56
Rob Avatar answered Oct 13 '22 02:10

Rob


It's not very safe to use properties directly. You can use the getRawBindings function for this.

Using the following code you get all bindings in a flattened array:

$q->getRawBindings();

Now you just need to filter out the orders.

like image 33
Jerodev Avatar answered Oct 13 '22 01:10

Jerodev