dtwk6019 2014-01-21 12:21
浏览 6

带有codeigniter的Datamapper可以保存多对多的关系

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

  • 写回答

1条回答 默认 最新

  • donglian4770 2014-01-22 17:17
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭