[eluser]Cannyp[/eluser]
Hi there,
I am having some difficulty saving back data to a joining table with habtm.
I have defined my schema and 2 classes as follows.
Code:
create table files (
id integer,
name varchar(20)
)
create table deliveries (
id integer,
dest varchar(20)
)
create table files (
id integer,
file_id integer,
delivery_id integer
)
class File extends IgnitedRecord {
var $table = "files";
var $habtm = array(
'table' => 'deliveries',
'fk' => 'file_id',
'name' => 'files',
'join_table' => 'file_deliveries',
'related_foreign_key' => 'delivery_id');
}
class Delivery extends IgnitedRecord {
var $table = "deliveries";
var $habtm = array(
'table' => 'files',
'fk' => 'delivery_id',
'name' => 'deliveries',
'join_table' => 'file_deliveries',
'related_foreign_key' => 'file_id');
}
and in my controller, I loop over some data in
$msg to save the data back to the database like so.
Code:
foreach($msg["files"] as $f)
{
$fdata["name"] = $f["name"];
$file_rec = $this->file->new_record($fdata);
$file_rec->save();
}
foreach($msg["deliveries"] as $d)
{
$ddata["dest"] = $d["dest"];
$del_rec = $this->delivery->new_record($ddata);
$del_rec->save();
}
EDIT: what I forgot to mention was, I have a second array in $d which relates to the file_deliveries. In this array, I have access to a reference to the file records already imported e.g.
Code:
foreach($msg["deliveries"] as $d)
{
$ddata["dest"] = $d["dest"];
$del_rec = $this->delivery->new_record($ddata);
$del_rec->save();
foreach ($d["filedeliveries"] as $fd)
{
print $fd["file_id"];
// need to save this to the joining table with the delivery_id
}
}
I can save the records back into the
files and
deliveries table fne but I cant work out how to insert the joining row without actually accessing the
id property of the
$del_rec and doing a
new_record() inside the 2nd foreach loop - but I dont want to do this as it kind of defeats the purpose.
Can anyone shed any light on how to setup the habtm relationships properly? I have tried playing around with
add_relationship() - which I have working in other parts of the code but I can't figure it out for habtm.
any pointers much appreciated.
thanks