0
0

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 3 years have passed since last update.

CakePHP2のfind('count')とgroupを組み合わせた時の返却値

Posted at

他の方にとっては基本中の基本かも知れませんが、CakePHP2のfind('count')とgroupを組み合わせた時の返却値について、注意点を書きます。
ほんと簡単な例として、次のアソシエーションを考えてみます!

顧客データ(Customer)

顧客ID 名前
1 山田太郎
2 鈴木次郎
3 田中三郎

注文データ(Order)

注文ID 顧客ID 品名
1 1 ラーメン
2 2 餃子
3 2 チャーハン

顧客と注文は一対多(hasMany)の関係があり、山田さんが「ラーメン」を鈴木さんが「餃子」と「チャーハン」を注文したデータがあるとします。

その時、各お客さんの注文数をカウントする時、次の処理になると思います。

$count = $this->Customer->find('count', array(
            'joins' => array(
                array(
                    'type' => 'INNER',
                    'table' => 'orders',
                    'alias' => 'Order',
                    'conditions' => array(
                        'Customer.orderId = Order.id'
                    )
                )
            ),
            'group' => 'Customer.id'
        ));

この時、山田さんの注文数は1、鈴木さんの注文数は2、さて田中さんの注文数は幾つになるでしょうか?

恥ずかしいことに自分は「count」という文字につられて、0になると想定していたところ、Falseが返却されました。Joinするデータがないのに、groupを指定しているためです。

以上、簡単な内容になりますが、そのカウント数を元に分岐処理する場合は気をつけましょうという話でした。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?