foreachの中でforeachしちゃうサンプルが下記。
foreachの中で更にforeach使ってしかもsql文も発行してる。
重さ的にもよろしくないです。
$where = [
'user_id' => $user_id,
'delete_flag' => 1,
];
$this->db->where($where);
/* リストが無かった時の処理 */
$template_list = $this->db->get('template')->result_array();
$template_ids = array_column($template_list, 'id');
$trigger_con = 0;
foreach ($template_ids as $value) {
$where = [
'template_id' => $value,
'delete_flag' => 1,
];
$this->db->where($where);
$template_message = $this->db->get('template_message')->result_array();
foreach ($template_message as $key => $val) {
if($val['trigger']){
$trigger_con++;
}
}
}
$field = [
'message_count' => $count
];
$where = [
'id' => $user_id
];
$this->db->where($where);
return $this->db->update('user', $field);
これを綺麗にしてみると下記になります。
チェックするべき箇所は下記になります。
array_column();
第一引数の中から、第二引数で指定したカラムを添え字にいれてくれる。
わざわざforeachしなくて済みます。
where_in
where IN()文を生成してくれる。
第一引数のカラムを第二引数で絞ります。
第二引数は配列可。
IS NOT NULL
NULLだった場合は数えない処理の為に入れた。
第三引数にfalseを指定する事でsql文をエスケープしなくなります。
num_rows
配列の数を返却してくれます。
綺麗さっぱりになったコードはこちら。↓
model
$where = [
'user_id' => $user_id,
'flag' => 1,
];
$this->db->where($where);
$template_list = $this->db->get('template')->result_array();
$template_ids = array_column($template_list, 'id');
$this->db->where_in('template_id', $template_ids);
$this->db->where('flag', 1);
$this->db->where('`trigger` IS NOT NULL', null, false);
$template_message = $this->db->get('sample_table')->num_rows();
$field = [
'con' => $count
];
$where = [
'id' => $user_id
];
$this->db->where($where);
return $this->db->update('user', $field);>num_rows();