7
8

More than 5 years have passed since last update.

FuelPHP でリレーションを組んだ孫モデルも一緒にsaveするやり方

Last updated at Posted at 2013-08-28

ざっと、こんな感じ?というのをメモ。
ソースを見た感じ、key_from と key_to を配列にすれば良いっぽい。
※ドキュメントのどっかに書いてあるかも

モデルたち
<?php
class Model_Parent extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'name',
    );

    protected static $_has_many = array(
        'child' => array(
            'key_from' => 'id',
            'model_to' => 'Model_Child',
            'key_to' => 'pid',
            'cascade_save' => true,
            'cascade_delete' => true,
        ),
    );
}

class Model_Child extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'pid',
        'name',
    );

    protected static $_has_many = array(
        'grandchild' => array(
            'key_from' => array('id', 'pid'),
            'model_to' => 'Model_GrandChild',
            'key_to' => array('cid', 'pid'),
            'cascade_save' => true,
            'cascade_delete' => true,
        ),
    );
}

class Model_GrandChild extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'cid',
        'pid',
        'name',
    );
}

saveするときは、孫を子に、子を親にセットする必要がある。

saveする
<?php
$grandchild = Model_GrandChild::forge();

$child = Model_Child::forge();
$child->grandchild[] = $grandchild;

$parent = Model_Parent::forge();
$parent->child[] = $child;

$parent->save();

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