【问题标题】:Cakephp db query result without tables's names, just plain result as in MySQL?没有表名的 Cakephp db 查询结果,只是像 MySQL 中的普通结果?
【发布时间】:2015-04-24 00:48:48
【问题描述】:

我正在使用 cakephp,我有一个模型

$db = $this->getDataSource();
$result = $db->fetchAll(
        'SELECT table1.id, 
            table1.title, 
            table1.buy_url, 
            table2.image_file as image, 
            table3.category_id as maincategory, 
            (table4.user_id = "71") AS isfavorite
        FROM table1
        INNER JOIN ...
        LEFT JOIN ...
        LEFT JOIN ...
        where ...);

    return $result;

我得到这样的结果:

{
  "table1": {
    "id": "132",
    "title": "Awesome",
  },
  "table2": {
    "image": "image_25398457.jpg"
  },
  "table3": {
    "maincategory": "3"
  },
  "table4": {
    "isfavorite": "1"
  }
}

但我不想显示表格的名称,我希望通过以下方式获得结果:

{
    "id": "132",
    "title": "Awesome",
    "image": "image_25398457.jpg"
    "maincategory": "3"
    "isfavorite": "1"
}   

我怎样才能做到这一点?

谢谢!

【问题讨论】:

    标签: php mysql sql json cakephp-2.3


    【解决方案1】:

    据我所知,结果是按表名分组的。

    最简单的选择是:

    $merged = call_user_func_array('array_merge', $result);
    

    另一种选择是:

    $db = $this->getDataSource();
    $result = $db->fetchAll(
        'SELECT * FROM (
            SELECT table1.id, 
                table1.title, 
                table1.buy_url, 
                table2.image_file as image, 
                table3.category_id as maincategory, 
                (table4.user_id = "71") AS isfavorite
            FROM table1
            INNER JOIN ...
            LEFT JOIN ...
            LEFT JOIN ...
            where ... '
        ) as final_table
    );
    
    return $result;
    

    这就是为什么你只会有类似的东西:

    {
       "final_table" : {
           "id": "132",
           "title": "Awesome",
           "image": "image_25398457.jpg"
           "maincategory": "3"
           "isfavorite": "1"
       }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多