We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Why query is outputted as an array of an array?

Hi I have the following code:

$order = $this->modelsManager
    ->createBuilder()
    ->columns([
        'order.id',
        'order.price',
        'order.userid',
        'products.id' as pid,
    ])
    ->from(['order' => 'Orders'])
    ->innerJoin('Products', 'order.productid = products.id', 'products')
    ->where(
        'order.id = :order_number:',
        ['order_number' => $request->getPost('order_number')]
    )
    ->limit(1)
    ->getQuery()
    ->execute()
    ->toArray();

    var_dump($order);exit();

Which outputs:

array(1) { [0]=> array(4) { ["id"]=> string(1) "1" ["price"]=> string(6) "12.01" ["userid"]=> string(2) "10" ["countryid"]=> string(3) "225" ["pid"]=> string(1) "2" } }

The output above is an array of an array, I wanted the $order to output:

array(4) { ["id"]=> string(1) "1" ["price"]=> string(6) "12.01" ["userid"]=> string(2) "10" ["countryid"]=> string(3) "225" ["pid"]=> string(1) "2" }

I want to find out why this happens as I would like to be consistent during development.

Thanks



93.7k
Accepted
answer

->execute() returns multiple results (array).

To fetch only 1 record you should be using ->getSingleResult() instead :)

Funny thing is that you just accepted my answer to your other question https://forum.phalcon.io/discussion/18061/query-builder-joins-error#C54751

The same thing in last comment :P



5.7k
edited Apr '18

I'm such a doughnut! lol



85.5k