Bonjour,
j'ai une requette MYSQL dans l'une de mes veuilles applications et je suis en train de la refaire en cakePHP mais je n'ai pa su ou mettre cette instruction.
Ancienne requette :
SELECT (IF(Day(date) = 1, valeur,0)) AS J1, (IF(Day(date) = 2, valeur,0)) AS J2
FROM users AS u
LEFT JOIN presences pr ON u.id = pr.id
AND (Month(pr.date) = 1 OR Month(pr.date) IS Null)
AND (Year(pr.date) = 2014 OR Year(pr.date) IS Null),
WHERE u.is_active = 1
GROUP BY u.id
Ps: (IF(Day(date) = x, valeur,0)) AS Jx ca se repete le nobre de jours du mois choisi.
Je suis dans le model USER avec hasAndBelongsToMany Presence ...
Nouvelle requette ??
Merci
Bonjour
Bon finalement, j'ai trouver la solution comme un grand :)
for ($i = 1; $i <= 30; $i++) {
$boucle .= 'SUM(IF(Day(PR.date) = ' . $i . ', PR.valeur,0)) AS J' . $i . ',';
}
$boucle = substr($boucle, 0, -1);
$result = $this->find('all', [
'fields' => ['username', $boucle],
'conditions' => ['User.group_id' => 3],
'joins' => [
[
'table' => 'presences_users',
'type' => 'LEFT',
'alias' => 'PRU',
'conditions' => [
'User.id = PRU.user_id'
]
],
[
'table' => 'presences',
'type' => 'INNER',
'alias' => 'PR',
'conditions' => [
'PRU.presence_id = PR.id'
]
]
],
]);
Le debug me renvoit :
array(
(int) 0 => array(
'User' => array(
'username' => 'rahma'
),
(int) 0 => array(
'J1' => '1',
'J2' => '1',
'J3' => '0',
'J4' => '0',
'J5' => '0',
'J6' => '0',
'J7' => '0',
'J8' => '0',
'J9' => '0',
'J10' => '0',
'J11' => '0',
'J12' => '0',
'J13' => '0',
'J14' => '0',
'J15' => '0',
'J16' => '0',
'J17' => '0',
'J18' => '0',
'J19' => '0',
'J20' => '0',
'J21' => '0',
'J22' => '0',
'J23' => '0',
'J24' => '0',
'J25' => '0',
'J26' => '0',
'J27' => '0',
'J28' => '0',
'J29' => '0',
'J30' => '0'
)
)
)
Peut être un truc du genre :
public $virtualFields = array(
'J1' => '(IF(Day(User.date) = 1, valeur,0))',
'J2'=> '(IF(Day(date) = 2, valeur,0))'
);
et, depuis le modèle
$this->find('all',[
'fields'=> ['J1','J2'],
'conditions'=> [
'User.Active'=> 1,
' OR' => [
' (Month(Presence.date)'=>1,
' Month(Presence.date)'=> null
],
'AND'=>[
'OR'=>[
'(Year(Presence.date)' =>2014,
'Year(Presence.date)'=> null
]
]
]
]);