Neo Inspiration

Feed Rss

CakePHP hasAndBelongsToMany でページング(SQL LIMIT)とかを設定する

12.04.2007, cakePHP, Model, O/Rマッピング, by .

ひさびさCake触ると いろいろ新しい発見があるものです。。

Cakeでは仕様上

hasOne > LEFT JOIN
belongsTo > LEFT JOIN
hasMany > IDを元に該当テーブルをSelect
hasAndBelongsToMany > IDを元に接続テーブルをSelect

という形なので
Modelのアソシエーション単位で、条件の書き方が変わってくるので
そのメモです。

例えば Post,Profile,Tag というModelで

Post->hasOne->Profile
Post->hasAndBelongsToMany->Tag

という形だと

Post Modelでこういう書き方が可能ですが

Post Model
$data = $this->findAll(
$conditions = “Profile.delFlg<>‘del’”
);

これはできません。

Post Model
$data = $this->findAll(
$conditions = “Tag.delFlg<>‘del’”
);

なぜなら hasOne はLEFT JOIN しているので
Profile というテーブル名が使えるのですが
hasAndBelongsToMany はID切り出しでSelectかけるため
PostモデルのFindAllからはテーブル名が使えないためです。

でこの場合はこうする

Post Model
$this->hasAndBelongsToMany['Tag']['conditions'] = “delFlg<>‘del’”;
$data = $this->findAll(
$conditions = “”,
);

hasManyの場合も同じ。

ようはアソシエーションを書き換えるわけですね。

なのでこれを利用して

Post Model
$this->hasAndBelongsToMany['Tag']['limit'] = “$page,10″;
$data = $this->findAll(
$conditions = “”,
);

とこう書けば、引数 $page を元にアソシエーション先のページングができるわけです。

CakePHP hasAndBelongsToMany でページング(SQL LIMIT)とかを設定する への2件のコメント

  1. Pingback: igarashiDesign::blog » Blog Archive » 【CakePHP1.3.6】hasManyでアソシエーションしたテーブルの中身を検索条件に

  2. Pingback: igarashiDesign::blog » Blog Archive » 【CakePHP1.3.6】hasManyでアソシエーションしたテーブルの中身を検索条件にする

コメントをどうぞ

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>