Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

ビヘイビア群

CounterCacheBehavior

例えばコメント数をエンティティが保存、削除されるたびに更新される。
belongsTo アソシエーションにしか効かない。

class CommentsTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('CounterCache', [
            'Articles' => ['comment_count']
        ]);
    }
}

細かいカスタマイズは以下
CounterCache - 3.x

TimestampBehavior

created や modified を更新してくれる。
Timestamp - 3.x

TranslateBehavior

翻訳

TreeBehavior

ツリー構造
テーブルがnullableなparent_idを持ち、整数、符号付きなlftとrghtを持つこと。

以下はまだ実感が無いので保留。
Tree - 3.x

使い方

class CategoriesTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('Tree');
    }
}
で読み込む。
再構築
>|php|
$categories = TableRegistry::get('Categories');
$categories->recover();
$node = $categories->get(1);
echo $categories->childCount($node);
$descendants = $categories->find('children', ['for' => 1]);

foreach ($descendants as $category) {
    echo $category->name . "\n";
}