Hòa Đinh
Hòa Đinh

Reputation: 1

Error when using custom query in cakephp?

I have using cakephp for my website. And i use sql server 2012 with it. I have confused that when i use:

$this->set('types',$this->Manager->query('select * from product_types'));

to get the array of all my product types the return array is:

Array
(

    [0] => Array
    (
        [0] => Array
        (
            [id] => 1
            [name] => hoa my pham
        )
    )

    [1] => Array
    (
        [0] => Array
        (
            [id] => 2
            [name] => hoa my
        )

    )

)

Why has the [0] instead of [product_types]????

Upvotes: 0

Views: 86

Answers (2)

mark
mark

Reputation: 21743

Please follow the documentation and tutorials available.

Then you will be able to just use

$this->set('managers', $this->Manager->find('all'));

for the very same thing - using a clean approach with wrapper functions and a sql server datasource.

For SqlServer there should be a datasource available, for example: https://github.com/cakephp/datasources/blob/2.0/Model/Datasource/Database/Sqlsrv.php

Upvotes: 1

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

This is from the CakePHP documentation:

To use the model name as the array key, and get a result consistent with that returned by the Find methods, the query can be rewritten:

$this->Picture->query("SELECT * FROM pictures AS Picture LIMIT 2;");

which returns:

Array
(
    [0] => Array
    (
        [Picture] => Array
        (
            [id] => 1304
            [user_id] => 759
        )
    )

    [1] => Array
    (
        [Picture] => Array
        (
            [id] => 1305
            [user_id] => 759
        )
    )
)

So you need:

$this->set('types',$this->Manager->query('select * from product_types as Product_Types'));

Source: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html

P.S.:

This syntax and the corresponding array structure is valid for MySQL only. Cake does not provide any data abstraction when running queries manually, so exact results will vary between databases.

Upvotes: 0

Related Questions