この質問は、対応する 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;
}
. . .