CakePHP在HABTM连接表上更新附加字段 [英] CakePHP update extra field on HABTM join table

查看:119
本文介绍了CakePHP在HABTM连接表上更新附加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HABTM连接表中更新(更新不重新创建)额外字段时遇到问题。我搜索了google和其他来源,但现在努力了4天。

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.

我有型号:

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表tutorial_categories_tutorial有id,tutorial_id,tutorial_category_id,order_by字段。

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

我想更新order_by字段,如:

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);

这是删除和创建连接表中的新记录,而不是设置order_by。我想更新记录,现在设置order_by的值。

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.

谢谢!

推荐答案

当您向HABTM连接模型添加了额外数据(顺序字段)时,简单的HABTM与CakePHP的关系。您实际需要设置的是 hasMany通过关系

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.

在你的情况下,你基本上会创建一个成员资格模型与教程ID,数据,您想要分配给它。然后你将定义相关性作为成员属于教程&类别。这本书可能有比我刚才解释的更好的例子!

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!

这样做的主要原因是每个成员资格记录被视为正常记录,没有HABTM行为附加到它,所以你可以编辑,删除和添加记录单独和容易。

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.

这篇关于CakePHP在HABTM连接表上更新附加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆