1

I'm new to datamapper. I have a problem on trying to duplicate a result into a new id.

This is a simplified table for my database:

Job Table

| id | property_id | name | type |
| 1  | 1           | abc  | i    |
| 2  | 2           | def  | ii   |

Property Table

| id | job_id | size |
| 1  | 1      | 90   |
| 2  | 2      | 40   |


How can I automatically duplicate a new job based on job id 1 into new job/property id like

Job Table

| id | property_id | name | type |
| 1  | 1           | abc  | i    |
| 2  | 2           | def  | ii   |
| 3  | 3           | abc  | i    |

Property Table

| id | job_id | size |
| 1  | 1      | 90   |
| 2  | 2      | 40   |
| 3  | 3      | 90   |

Thanks for helping! :)

tereško
  • 58,060
  • 25
  • 98
  • 150
Shah Erhan
  • 573
  • 5
  • 7

2 Answers2

3

In the documentation for DataMapper Overzealous Edition: http://datamapper.wanwizard.eu/pages/clonecopy.html There's clone and copy, copy will clear the id. Here's their example, just skip the part of making changes:

// Let's save a new hosting plan
$p = new Plan();

$p->name = 'The 100GB Plan';
$p->storage = 1000;
$p->bandwidth = 2000;
$p->databases = 5;
$p->domains = 5;
$p->emails = 50;

$p->save();

// Now, lets make a copy of that saved plan and base a new one off of it
$p = $p->get_copy();

// Change only what we need to
$p->name = 'The Big 150GB Plan';
$p->storage = 1500;
$p->bandwidth = 2500;

// And now save a new record
$p->save();
Matthew
  • 15,282
  • 27
  • 88
  • 123
  • Thanks for the help it works! Now I just have to figure out myself how to duplicate all other table relation with the new id :) – Shah Erhan Nov 03 '11 at 08:24
1

You can also just modify the object you retrieve, and then use save_as_new() to save it as a new record.

WanWizard
  • 2,574
  • 15
  • 13
  • How do I use save_as_new() without the id I'm trying to copy? Thanks. Is it just directly using: $j = new Job(); $j->where('id', 1)->get(); $j->save_as_new(); Thanks a lot – Shah Erhan Nov 03 '11 at 07:40
  • Same here using 1.8.2 - just had to clear the `id` manually and use `save()`, `save_as_new()` seemed to do nothing. – Wesley Murch Jul 26 '12 at 02:20