保存与Cakephp 3的关联 [英] Save associations with Cakephp 3

查看:255
本文介绍了保存与Cakephp 3的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题与CakePHP 3和保存新的实体及其与一个操作的关联。

I have a problem with CakePHP 3 and saving new entity and its associations with one operation.

在我看来,我做的像文档中推荐的。

In my opinion I do it like recommended in the documentation.

这里是我的控制器:

$articles = TableRegistry::get('Articles');       
$article = $articles->newEntity($this->request->data);  

if ($this->request->is('post')) {            

    $valid = $articles->validate($article, [
        'associated' => ['Topics']
    ]);

    if ( $valid ) {
        $articles->save($article, [
            'validate' => false,
            'associated' => ['Topics']
        ]);
    }
}  

这是我的模型:

class ArticlesTable extends Table {   
    public function initialize(array $config) {        
        $this->primaryKey('article_id');
        $this->belongsTo ( 'Topics', [
            'targetForeignKey'  => 'topic_id'
        ]);
    }
}

class TopicsTable extends Table {  
    public function initialize(array $config) {        
        $this->primaryKey('topic_id');  
        $this->hasMany ( 'Articles', [
            'targetForeignKey'  => 'article_id'
        ]);    
}  

这是我的数据库:

CREATE TABLE `articles` (
  `article_id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`article_id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

CREATE TABLE `topics` (
  `topic_id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_title` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

我的表单看起来像这样:

MY form looks like that:

<input type="text" id="articles-heading" maxlength="45" required="required" name="Articles[heading]">
<input type="text" id="articles-topics-topic-title" list="topics" name="Articles[Topics][topic_title]"> 

我想创建一个包含所有关联的表单,并保存一个请求。

I want to create a form which contains all the associations and save it with one request.

推荐答案

缺少列



没有名为

Missing columns

There is no column named heading in your articles table.

您的配置看起来不对, targetForeignKey 是用于 BelongsToMany 关联, c $ c> article_id (另一个表的主键) 中的外键 >关联,它是 topic_id ,并且没有必要在遵循命名约定时指定它。

Your configuration looks wrong, targetForeignKey is for BelongsToMany associations, and article_id (the primary key of the other table) is not the foreign key in an Topic hasMany Comment association, it's topic_id, and it's not necessary to specify it when you're following the naming conventions.

所以当指定外键,它应该看起来像这样:

So when specifiying the foreign keys at all, it should look something like this:

class ArticlesTable extends Table {   
    public function initialize(array $config) {        
        $this->primaryKey('article_id');
        $this->belongsTo ( 'Topics', [
            'foreignKey' => 'topic_id'
        ]);
    }
}

class TopicsTable extends Table {  
    public function initialize(array $config) {        
        $this->primaryKey('topic_id');  
        $this->hasMany ( 'Articles', [
            'foreignKey' => 'topic_id'
        ]);   
    } 
} 

你可以避免很多混乱,如果你遵守惯例并命名您的主键 id

You could avoid a lot of confusion if you'd stick to the convention and name your primary keys id.

另请参阅

  • Cookbook > Models > Table Objects > Basic Usage
  • Cookbook > Models > Table Objects > HasMany Associations

由于您尝试保存非默认字段(即 Topic Topic 主键),您必须通过 newEntity 使字段可供大量分配使用。这可以通过 Entitiy :: $ _ accessible 属性来实现,对于该实体的每个实例都是永久的,直到在运行时被覆盖

Since you are trying to save non-default fields (that is Topic data instead of Topic primary key), you'll have to make the field accessible for mass assignment via newEntity. This is possible for example via the Entitiy::$_accessible property, which is permanent for every single instance of that entity until overriden at runtime

class Article extends Entity {
    protected $_accessible = [
        // ...
        'topic' => true
    ];
}

或使用 accessibleFields 的选项>

$article = $articles->newEntity($this->request->data, [
    'accessibleFields' => [
        'topic' => true
    ]
]);  

另请参阅

  • Cookbook > Models > Entities > Mass Assignment
  • API > Cake\ORM\Table::newEntity()

最后,您的表单数据格式不正确,为了匹配实体属性,默认情况下名称应为小写和下划线,并且它们应该是单数形式(除非它是 hasMany belongsToMany 关联),即应该是 article 而不是文章主题,实际上没有必要使用<$ c $

Finally your form data is incorrectly formatted, names should by default be lowercase and underscored in order to match the entities properties, and they should be singular (unless it's a hasMany or belongsToMany association), ie it should be article and topic instead of Articles and Topics, also it's actually not necessary to use article at all.

echo $this->Form->input('heading');
echo $this->Form->input('topic.topic_title');





<input type="text" name="heading">
<input type="text" name="topic[topic_title]"> 

另请参阅 Cookbook> Helpers> FormHelper>字段命名惯例

See also Cookbook > Helpers > FormHelper > Field Naming Conventions

这篇关于保存与Cakephp 3的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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