简体   繁体   English

在没有视图的情况下关联 CakePHP HABTM 模型

[英]Associating CakePHP HABTM models without a view

I'm writing an import from CSV and have been able to successfully manually set data fields on a model in code by using the $this->Book->set() function and passing it a hash containing all of the fieldName => value pairings. I'm writing an import from CSV and have been able to successfully manually set data fields on a model in code by using the $this->Book->set() function and passing it a hash containing all of the fieldName => value配对。

How do I create habtm associations in code?如何在代码中创建 habtm 关联? All the examples I've seen in the documentation are based on the $this->data returned from a form in the view.我在文档中看到的所有示例都基于从视图中的表单返回的$this->data Because my data is coming from a csv file and not a view I can't use this!因为我的数据来自 csv 文件而不是视图,所以我不能使用它!

So in the following example:所以在下面的例子中:

// Book habtm Tags
// Tag habtm Books

$this->Book->create();
$this->Book->set(
    array(
      'author' => 'tolkein',
      'title' => 'lord of the rings')
    );

$arrayOfTagIds = array(1, 5, 6);
// Do something with $arrayOfTagIds...
$this->Book->save();

How would I associate the $arrayOfTagIds with the Book?我如何将 $arrayOfTagIds 与 Book 相关联?

Instead of using set to add data to the new entity and save to save it, use create and saveAll .不要使用set将数据添加到新实体并save以保存它,而是使用createsaveAll In the example below, replace the BookTag model with the name of the model used in the relationship between books and tags.在下面的示例中,将BookTag model 替换为书籍和标签之间的关系中使用的 model 的名称。 You'll also need to change tag_id to match the name of the field that represents the tag's id.您还需要更改tag_id以匹配代表标签 ID 的字段名称。

Example:例子:

$book = array(
  'Book' => array(
    'author' => 'tolkein',
    'title' => 'lord of the rings'
  ),
  'Tag' => array(
    'Tag' => array(1,5,6);
  )
);

$this->Book->create($book);
$this->Book->saveAll();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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