Skip to content

Instantly share code, notes, and snippets.

@half2me
Last active January 27, 2016 20:53
Show Gist options
  • Save half2me/22c0ada47febc26ce8cd to your computer and use it in GitHub Desktop.
Save half2me/22c0ada47febc26ce8cd to your computer and use it in GitHub Desktop.
Associated model not getting linked with custom finder method
<?php
// In my controller:
$delivery = $this->Deliveries->get($id, [
'contain' => ['Warehouses', 'DeliveryNotes', 'Orders', 'Products' => function ($q) {
return $q->find('filtered', ['options' => ['group' => 'ean']])
->select(['Products.id', 'ProductInfo.sku', 'ProductInfo.id', 'Products.size', 'Products.product_info_id'])
->contain('ProductInfo');
}]
]);
Delivery model is populated, but associated products[] is empty. Running the generated SQL in a console returns the data perfectly.
// Generated SQL:
SELECT
Deliveries.id AS `Deliveries__id`,
...
SELECT
(
COUNT(Products.id)
) AS `pcs`,
(
COUNT(Products.reservation_id)
) AS `reserved`,
Products.id AS `Products__id`,
ProductInfo.sku AS `ProductInfo__sku`,
Products.size AS `Products__size`
FROM
products Products
INNER JOIN product_info ProductInfo ON ProductInfo.id = (Products.product_info_id)
WHERE
Products.delivery_id in (69)
GROUP BY
Products.product_info_id,
Products.size
<?php
// Custom finder method in Table
public function findFiltered(Query $query, array $options)
{
if (!empty($options['options']['group'])) {
switch ($options['options']['group']) {
case 'ean':
$query
->group(['Products.product_info_id', 'Products.size'])
->select(['pcs' => $query->func()->count('Products.id')])
->select(['reserved' => $query->func()->count('Products.reservation_id')]);
break;
}
}
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment