Welcome Guest, Not a member yet? Register   Sign In
best process for saving a new object and its relation in a single call using datamapper
#1

[eluser]johnmerlino[/eluser]
Hey all,

I read the datamapper documentation where it says you can save a new object and its relation in a single call:

Code:
// Create new User
$u = new User();

// Enter values into required fields
$u->username = "foo";
$u->password = "bar";
$u->email = "[email protected]";

// Get country object for Australia
$c = new Country();
$c->where('name', 'Australia')->get();

// Save new user and also save a relationship to the country
$u->save($c);

I presume this technique only applies when you create a new object but update another object at the same time. But it doesn't work when creating two new objects:

Code:
$user = new User();
    $user->first_name = $this->input->post('first_name');
    $user->last_name = $this->input->post('last_name');
    $user->email = $this->input->post('email');
    $user->setPassword($this->input->post('password'));
    $user->role_id = $role['registered_user'];
    $user->getActivation();
                
    $vanity_url = new VanityUrl();
    $vanity_url->url = $this->input->post('user_name');
        $user->save($vanity_url);

This writes a new users record to database but not a vanity_urls record. In order to write them both concurrently, I had to do this:

Code:
user = new User();
                $user->first_name = $this->input->post('first_name');
                $user->last_name = $this->input->post('last_name');
                $user->email = $this->input->post('email');
                $user->setPassword($this->input->post('password'));
                $user->role_id = $role['registered_user'];
                $user->getActivation();
                $user->save();
                
                $vanity_url = new VanityUrl();
                $vanity_url->url = $this->input->post('user_name');
                $vanity_url->user_id = $user->id;
                $vanity_url->save();

The process above works, but not the datamapper documentation example. I presume that's only for when creating a new object in one table but updating one in another.

Is my understanding correct?

Thanks for response.
#2

[eluser]WanWizard[/eluser]
This is quite logical. When you call save
Code:
$user->save($vanity_url);
the vanity_url doesn't have an 'id' yet, which is required to make the relation.

You can try to use the fact that all Datamapper methods return the object, perhaps this works (not tested)
Code:
$user->save($vanity_url->save());

In your second example, you save both objects indivudually, but never make the relation, so you should add
Code:
$user->save($vanity_url);
after you have saved the vanity_url object. And then there is no need to manually assign the user_id.




Theme © iAndrew 2016 - Forum software by © MyBB