简体   繁体   中英

Many-To-Many relationship save fails

I have this Many-To-Many relation:

M2M

These are my Models:

Productvariant

class Productvariant extends DataMapper {

    var $has_many = array('propertyvalue');
    var $has_one = array('product');

}

Propertyvalue

class Propertyvalue extends DataMapper {

    var $has_many = array('productvariant');
    var $has_one = array('property');

}

Controller

$productvariant = new Productvariant(1);
$prodval = new Propertyvalue(1);
$productvariant->save($prodval);

Message

Unable to relate productvariant with propertyvalue.

Only thing I can find in the documentation is self Many-To-Many relationship and I seem to misread how they want you to use the models in that fashion.

Do I need to define a model for the extra table too?

==========================

UPDATE

I made an in-between Model for Many-To-Many relationship;

Model

class Productvariant_propertyvalues extends DataMapper {

    var $table = '__productvariants_propertyvalues';

    var $has_one = array('productvariant', 'propertyvalue');

}

Controller

$productvariant = new Productvariant(1);
$propval = new Propertyvalue(1);

$pv_vals = new Productvariant_propertyvalues();
$pv_vals->save(array($productvariant, $propval));

It works now, but shouldn't this be doable without the extra Model ?

You either have a many-to-many between Productvariant and Propertyvalue, and then you define them as you did. Datamapper will automatically look for a junction table called "productvariants_propertyvalues", which contains the foreign keys to the two tables.

So your setup should work. They only issue that could pop up is that the CI plural() function that datamapper uses doesn't produce the correct table name, causing the not-found error to popup.

If you create an in-between model, you split the many-to-many into two one-to-many's. Not a problem, but whether or not you need it depends on your application design.

edit: I now see you have prefixed the table name with a double underscore. Datamapper will not generate that, so that is why the junction table can not be found. Either remove those, or switch to an advanced relationship definition in which you define the "join_table" manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM