there doesn't seem to be an extra method for adding has_one relations, but if you want to stick with the ORM, you could do it the other way around:
$g->cars()->add($c);
Pergunta
I cannot find a clue on how to correctly save a has_one relation in Silverstripe.
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();
But this code does nothing, no error, but also the relation is not created in the DB.
What I could to is this:
$c->GarageID = $g->ID;
$c->write();
But this does not seem very ORM like...
Solução
there doesn't seem to be an extra method for adding has_one relations, but if you want to stick with the ORM, you could do it the other way around:
$g->cars()->add($c);
Outras dicas
This question is especially relevant if you have no corresponding has_many relationship, but want to establish an unsaved relationship between two objects.
What worked for me was creating a property, under the initial class, and assigning the unsaved relating object against that. The major limitations are:
Fortunately, my case was a very simple object.
Example:
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;
}
. . .