如果您没有对应的 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;
}
. . .