2

Silverstripe で has_one リレーションを正しく保存する方法の手がかりが見つかりません。

class Car extends DataObject {
  $has_one = array(
     'garage'=>'Garage';
  );
}

class Garage extends DataObject {
  $has_many = array(
     'cars'=>'Car';
  );
}
// let's say I have these records in the DB
$g = Garage::get()->ByID(111);
$c = Car::get()->ByID(222);

// I want to do sth like this to define the relation
$c->Garage = $g;
$c->write();

しかし、このコードは何もせず、エラーも発生しませんが、関係は DB に作成されません。

私ができることはこれです:

$c->GarageID = $g->ID;
$c->write();

しかし、これは非常にORMのようには見えません...

4

2 に答える 2

3

has_one リレーションを追加するための追加の方法はないようですが、ORM に固執したい場合は、逆の方法で行うことができます。

$g->cars()->add($c);
于 2013-09-27T06:41:48.947 に答える
0

この質問は、対応する has_many 関係がなく、2 つのオブジェクト間に保存されていない関係を確立したい場合に特に関連します。

私にとってうまくいったのは、初期クラスの下にプロパティを作成し、それに対して保存されていない関連オブジェクトを割り当てることでした。主な制限は次のとおりです。

  • オブジェクトの最新のインスタンスへの参照は、常にプロパティである必要があります。そうしないと、同時実行の問題が発生します。
  • 割り当てられる大きなオブジェクトは、使用可能なメモリを圧迫します。

幸いなことに、私のケースは非常に単純なオブジェクトでした。

例:

Car.php:

. . .

private static $has_one = array(
    'Garage' => 'Garage'
);

private $unsaved_relation_garage;

protected function onBeforeWrite() {

    parent::onBeforeWrite();

    // Save the unsaved relation too
    $garage = $this->unsaved_relation_garage;

    // Check for unsaved relation
    // NOTE: Unsaved relation will override existing
    if($garage) {

        // Check if garage already exists in db
        if(!$garage->exists()) {

            // If not, write garage
            $garage->write();
        }

        $this->GarageID = $garage->ID;
    }
}

/**
 * setGarage() will assign a written garage to this object's has_one 'Garage',
 * or an unwritten garage to $this->unsaved_relation_garage. Will not write.
 *
 * @param Garage $garage
 * @return Car
 */
public function setGarage($garage) {

    if($garage->exists()) {
        $this->GarageID = $garage->ID;
        return $this;
    }

    $this->unsaved_relation_garage = $garage;
    return $this;
}

/**
 * getGarage() takes advantage of the variation in method names for has_one relationships,
 * and will return $this->unsaved_relation_garage or $this->Garage() dependingly.
 *
 * @return Garage
 */
public function getGarage() {

    $unsaved = $this->unsaved_relation_garage;

    if($unsaved) {
        return $unsaved;
    }

    if($this->Garage()->exists()) {
        return $this->Garage();
    }

    return null;
}

. . .
于 2016-09-22T06:10:31.510 に答える