0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

codeigniter foreachの中でsql発行したくない。。where_in使ってみる

0
Posted at

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();
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?