1
votes

I'm using CakePHP 3.3 and try to get data by join table

$this->find()
->select([
    'TableA.id',
    'TableA.user_id',
    'TableA.note',
    'TableB.log_date'
])
->where([
    'TableA.user_id' => $userId
])
->join([
    'table' => 'table_b',
    'alias' => 'TableB',
    'conditions' => 'TableA.table_b_id = TableB.id',
]);

I try to var_dump() result var_dump($result->toArray());die; My array display like this:

    "data": [
    {
        "id": 1317,
        "user_id": 331,
        "note": "Take note",
        "TableB": {
            "log_date": "2017-11-16"
        }
      },
      {
        "id": 1318,
        "user_id": 331,
        "note": "Take note",
        "TableB": {
            "log_date": "2017-11-16"
        }
      }
  ],

My result has nested in TableB. How I can remove nested and display like this:

    "data": [
      {
        "id": 1317,
        "user_id": 331,
        "note": "Take note",
        "log_date": "2017-11-16"
      },
      {
        "id": 1318,
        "user_id": 331,
        "note": "Take note",
        "log_date": "2017-11-16"
      }
   ],

Could I get all data in same level in array? Thanks for reading!

1

1 Answers

0
votes

You can make alias for joined fields by using associative keys in select()

$result = $this
    ->Articles
    ->find()
    ->select([
        'Articles.id', 
        'user_id' => 'users.id' 
    ])
    ->join([
        'table' => 'users', 
        'conditions' => 'users.id = Articles.user_id'
    ])
    ->toArray(); 

The sample of result:

[{"id":26,"user_id":2},{"id":27,"user_id":2}]