Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp db query result without tables's names, just plain result as in MySQL?

I am using cakephp and I have a model

$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;

I am obtaining a result like this:

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

but I dont want to show the tables's names, I would prefer to obtain the result in the following way:

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

How can I achive this ?

Thanks !

like image 447
BlackBishop Avatar asked Nov 01 '22 09:11

BlackBishop


1 Answers

From what I can see, the results are grouped by table name.

Simplest option is:

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

Another option is:

$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;

This why you would only have something like:

{
   "final_table" : {
       "id": "132",
       "title": "Awesome",
       "image": "image_25398457.jpg"
       "maincategory": "3"
       "isfavorite": "1"
   }
} 
like image 162
Alex Tartan Avatar answered Nov 12 '22 22:11

Alex Tartan