Andreas Daoutis Andreas Daoutis - 2 years ago 346
SQL Question

CakePHP 3: How to automatically get fields from leftJoin?

I have two tables. Cars and tires. Tires can(!) belong to a car. My tables looks like:


id | car_id
1 | 17
2 | NULL


id | name
17 | BMW
18 | Mercedes

From my understanding, if I want to get all(!) tires (including the car they belong to, if available) I can't create a inner join (so I can't use contain). I need to use a left join. But that way I have no idea how to automatically select all fields on table cars.

Query I do:

$query = $this->Tires->find('all');
['Cars' => 'cars'],
[' = Tires.car_id']

// brings this SQL query
SELECT AS `Tires__id`, Tires.car_id AS `Tires__car_id`
FROM tires Tires
LEFT JOIN cars Cars ON = Tires.car_id

But how do I automatically get all fields from cars as well?

burzum actually gave me the solution which I quickly want to detail out since I don't think it is well solved by cake...

In order to achieve what I tried to do, I need to add the following code:

// you need to pass each model you want to get fields for

The car in its tire looks like this:

'Cars' => [
'id' => '17',
'name' => 'BMW'

If I did a contain, it would look like this:

'car' => object(App\Model\Entity\Car) {
'id' => (int) 17,
'name' => 'BMW',
'[new]' => false,
'[accessible]' => [
'*' => true
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Cars'

So, I can work with that. Still, I don't understand the different output...

Answer Source

Example taken from the above URL:

// Only all fields from the articles table including
// a calculated slug field.
$query = $articlesTable->find();
    ->select(['slug' => $query->func()->concat(['title', '-', 'id'])])
    ->select($articlesTable); // Select all fields from articles

So in your case you need to pass an instance of the cars table to a select() call.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download