I have two tables. Cars and tires. Tires can(!) belong to a car. My tables looks like:
Tires:
id  |  car_id
-------------
1   |  17
2   |  NULL
Cars:
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');
$query->leftJoin(
    ['Cars' => 'cars'],
    ['Cars.id = Tires.car_id']
);
// brings this SQL query
SELECT Tires.id AS `Tires__id`, Tires.car_id AS `Tires__car_id`
FROM tires Tires 
LEFT JOIN cars Cars ON Cars.id = Tires.car_id
But how do I automatically get all fields from cars as well?
UPDATE 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:
$query
  // you need to pass each model you want to get fields for
  ->select($this->Tires)
  ->select($this->Tires->Cars);
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...
http://book.cakephp.org/3.0/en/orm/query-builder.html#selecting-all-fields-from-a-table
Example taken from the above URL:
// Only all fields from the articles table including
// a calculated slug field.
$query = $articlesTable->find();
$query
    ->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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With