简体   繁体   中英

Datamapper with codeigniter save many to many relationship

I have three table company,group and company_group.

I am getting values from post while saving a company.

In my company form i have multiple select box which has a list of group.

My company is getting saved correct-ally but now i want to add record in company_group table with last inserted id of company and selected group.

I have set up has_many in both models company and group but cannot save multiple records in company_group table so help me with this.

Company model

class Company extends DataMapper {
var $has_one=array("group");
function __construct() {
   parent::DataMapper();
}
}

group model

class Group extends DataMapper {
 var $has_many=array("company");
function __construct() {
    parent::DataMapper();
    }
}

company controller

class Company_c extends CI_Controller {
 public function index() {

    $company = new company();
    $group=new group();
    $company->id=1;
    $group->id=2;
    $group->id=4;
    $company->save($group);

  }

}

Please help me with this

You're not loading the company or group objects properly. When you instantiate a company, you need to do:

$company = new Company();
$company->where('id', 1)->get();

or , quicker as a shorthand (as long as you use the id property):

$company = new Company(1);

(Note that the class name is case-sensitive).

You then do the same with the group(s) you want to load:

$groups = new Group();
$groups->where_in('id', array(2, 4)->get();

Then, when both are instantiated, you can save the company and its group(s) in one go:

$company->save($groups);

Make sure you go through the DataMapper docs thoroughly, it couldn't really be explained more clearly: http://datamapper.wanwizard.eu/pages/save.html#Relationship

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