CakePHP update extra field on HABTM join table

懵懂的女人 提交于 2019-12-20 05:44:13

问题


I have problem with updating (better updating not recreating) extra field in HABTM join table. I searched google and other sources, but struggled for 4 days now.

I have models:

class Tutorial extends AppModel {
  var $hasAndBelongsToMany = array(
    'TutorialCategory' => array(
      'with' => 'TutorialCategoriesTutorial',
      'order' => 'TutorialCategoriesTutorial.order_by ASC',
      'unique' => true,
  );
}

class TutorialCategory extends AppModel {
  var $hasAndBelongsToMany = array(
    'Tutorial' => array(
      'with' => 'TutorialCategoriesTutorial',
      'unique' => true,
  );
}

join table tutorial_categories_tutorial have id, tutorial_id, tutorial_category_id, order_by fields.

I am trying to update order_by field like:

$order = 1;
foreach($tutorials as $i => $tutorial) {
  $this->data[$i]['Tutorial']['id'] = $tutorial['Tutorial']['id];
  $this->data[$i]['TutorialCategory']['id'] = $tutorial['TutorialCategory']['id];
  $this->data[$i]['TutorialCategoriesTutorial']['order_by'] = $order;

  ++$order;
}
$this->Tutorial->bindModel(array('hasMany' => array('TutorialCategoriesTutorial')));
$saved = $this->Tutorial->saveAll($this->data);

This is deleting and crating new records in join table, but not setting order_by at all. I want to update record and set now order_by value. I tried hasMany through but no luck.

Please help and/or give advice and explanation.

Thank you!


回答1:


As you have added extra data (order field) to the HABTM join model, you have actually exceeded the capabilities of a simple HABTM relationship with CakePHP. What you actually need to setup is a hasMany Through relationship.

In your case you'll basically make a "membership" model with Tutorial ID, catergory id and as much data as you want to assign to it. You will then define the relatioships as Membership belongsTo Tutorial & Category. The book probably has a better example than what I've just explained!

The main reason for this is that each "membership" record is treated as a normal record with no HABTM behaviour attached to it, so you can edit, delete and add records individually and easily.



来源:https://stackoverflow.com/questions/6677602/cakephp-update-extra-field-on-habtm-join-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!