Silverstripe将对象添加/保存到has_one关系

时间:2013-09-27 00:10:10

标签: php orm silverstripe has-many has-one

我无法找到如何在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 ......

2 个答案:

答案 0 :(得分:3)

似乎没有额外的方法来添加has_one关系,但是如果你想坚持使用ORM,你可以反过来这样做:

$g->cars()->add($c);

答案 1 :(得分:0)

如果您没有相应的has_many关系,但希望在两个对象之间建立未保存的关系,则此问题尤其重要。

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

  • 您对该对象的最新实例的引用需要始终是属性,否则您将获得可靠性问题。
  • 正在设置的大型物体会降低您的可用内存。

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

示例:

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;
}

. . .