Commit 19e9e9f5 authored by Jens Segers's avatar Jens Segers

Adding associate for embedsOne, fixes #215

parent 96f07a9f
......@@ -35,6 +35,25 @@ class EmbedsOne extends EmbedsOneOrMany {
return ($embedded and $embedded[$primaryKey] == $key);
}
/**
* Associate the model instance to the given parent, without saving it to the database.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return \Illuminate\Database\Eloquent\Model
*/
public function associate(Model $model)
{
// Create a new key if needed.
if ( ! $model->getAttribute('_id'))
{
$model->setAttribute('_id', new MongoId);
}
$this->setEmbedded($model->getAttributes());
return $model;
}
/**
* Save a new model and attach it to the parent model.
*
......@@ -51,7 +70,7 @@ class EmbedsOne extends EmbedsOneOrMany {
$result = $this->query->update(array($this->localKey => $model->getAttributes()));
if ($result) $this->setEmbedded($model->getAttributes());
if ($result) $this->associate($model);
return $result ? $model : false;
}
......@@ -66,7 +85,7 @@ class EmbedsOne extends EmbedsOneOrMany {
{
$result = $this->query->update(array($this->localKey => $model->getAttributes()));
if ($result) $this->setEmbedded($model->getAttributes());
if ($result) $this->associate($model);
return $result ? $model : false;
}
......
......@@ -414,6 +414,21 @@ class EmbeddedRelationsTest extends TestCase {
$this->assertEquals('Jim Doe', $user->father->name);
}
public function testEmbedsOneAssociate()
{
$user = User::create(array('name' => 'John Doe'));
$father = new User(array('name' => 'Mark Doe'));
$father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher'));
$events->shouldReceive('until')->times(0)->with('eloquent.saving: '.get_class($father), $father);
$father = $user->father()->associate($father);
$father->unsetEventDispatcher();
$this->assertNotNull($user->_father);
$this->assertEquals('Mark Doe', $user->father->name);
}
public function testEmbedsOneDelete()
{
$user = User::create(array('name' => 'John Doe'));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment