dow5001 2013-05-18 11:09
浏览 37
已采纳

在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]????

  • 写回答

2条回答 默认 最新

  • dongzuan4917 2013-05-18 11:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?