Skip to content

Instantly share code, notes, and snippets.

@damianoporta
Last active November 2, 2015 23:37
Show Gist options
  • Save damianoporta/c3aa77107948eae7dd76 to your computer and use it in GitHub Desktop.
Save damianoporta/c3aa77107948eae7dd76 to your computer and use it in GitHub Desktop.
<?php
/**
* Recupera i tags associati alla tabella
* Le opzioni che vengono utilizzate sono:
*
* - association: (obbligatorio) Nome dell'associazione da utilizzare per il recupero dei tags
* - matching: (opzionale) Utilizzato per modificare il tipo di query da eseguire
* matching() o contain()
* - query_conditions: (opzionale) Array con le condizioni di filtro da applicare
* - query_order: (opzionale) Array con le condizioni di ordinamento da applicare
*
* @param Query $query
* @param array $options
* @return Query
*/
public function findTags(Query $query, array $options)
{
// Se non c'è alcuna associazione restituisco la query senza procedere
if (empty($options['association'])) {
return $query;
}
if (empty($options['matching'])) {
// Contain
return $query->contain([$options['association'] => function ($q) use ($options) {
// Condizioni
if (!empty($options['query_conditions'])) {
$q->where($options['query_conditions']);
}
// Order
if (!empty($options['query_order'])) {
$q->order($options['query_order']);
}
return $q->contain('Tags');
}]);
} else {
// Matching
return $query
->join([
'table' => 'tags_associations',
'alias' => $options['association'],
'type' => 'INNER',
'conditions' => [
"{$options['association']}.foreign_key = Ads.id",
"{$options['association']}.model" => "Ads",
]
])
->join([
'table' => 'tags',
'alias' => "{$options['association']}Tags",
'type' => 'INNER',
'conditions' => [
"{$options['association']}.tag_id = {$options['association']}Tags.id",
]
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment