Seo tools

Neo Inspiration

  • Search

    • About Me

      • inspi 改め
        jakk@webアーキテクト(自称)
        php,javascript,seoなど
        得意技は extract();



  • Categories

  • Ranking

  • Comments

  • Others


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

    ひさびさ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 を元にアソシエーション先のページングができるわけです。


    Leave a Reply

    2008/11/22 07:49:58