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();

但是这段代码什么都不做,没有错误,而且关系也没有在数据库中创建。

我能做到的是:

$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 关系,但想在两个对象之间建立未保存的关系,则此问题尤其重要。

对我有用的是在初始类下创建一个属性,并为此分配未保存的相关对象。主要限制是:

  • 您对对象的最新实例的引用必须始终是属性,否则您会遇到并发问题。
  • 分配的大型对象会占用您的可用内存。

幸运的是,我的案例是一个非常简单的对象。

例子:

汽车.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 回答