Skip to content

Instantly share code, notes, and snippets.

@half2me
Created December 30, 2015 15:42
Show Gist options
  • Save half2me/f047e8e49c54b890ece2 to your computer and use it in GitHub Desktop.
Save half2me/f047e8e49c54b890ece2 to your computer and use it in GitHub Desktop.
Extract where
$allowedIds = $this->Websites->Products->find()
->extract(['id'])
->where(['reservation_id IS' => null]) // Product is not already reserved
->where(['size' => $converter->convert($request['size_eu'], $gender['gender'])]) // Product size matches
->where(['id IN' => TableRegistry::get('ProductsWebsites')->find() // Product belongs to the Website
->select(['product_id'])
->where(['website_id' => $website->id])
])
->where(['product_info_id IN' => $this->Websites->Products->ProductInfo->find() // Product sku matches
->select('id')
->where(['sku' => $request['sku']])
])
->toList();
debug($allowedIds);
@ionas
Copy link

ionas commented Dec 30, 2015

// NOTE: Move this to a model layer method and call it from there. Building queries in the controller is mostly bad. Trust me, I build a ton of bad cake2 apps that way :p
$allowedIds = $this->Websites->Products->find()
    ->where(['reservation_id IS' => null]) // Product is not already reserved
    ->where(['size' => $converter->convert($request['size_eu'], $gender['gender'])]) // Product size matches
    // NOTE: You might want to setup assocations correctly and/or use ->innerJoinWith(), instead of:
    ->where(['id IN' => TableRegistry::get('ProductsWebsites')->find() // Product belongs to the Website
        ->select(['product_id'])
        ->where(['website_id' => $website->id])
    ])
    // NOTE: You might want to setup assocations correctly and/or use ->innerJoinWith(), instead of:
    ->where(['product_info_id IN' => $this->Websites->Products->ProductInfo->find() // Product sku matches
        ->select('id')
        ->where(['sku' => $request['sku']])
    ])
    ->all()
    ->toArray();
debug($allowedIds);

@half2me
Copy link
Author

half2me commented Dec 30, 2015

Thanks @lonas Is there some way I can use this have an update() statement with a ->where(['id IN' => $allowedIds]); ?
It would be nice to not have to do 2 queries, but have it as a sub-query.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment