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.
There is no column named heading in your articles table.
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'
]);
}
}
You could avoid a lot of confusion if you'd stick to the convention and name your primary keys id.
See also
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
];
}
or by using the accessibleFields option for Table::newEntity(), which only applies to that one single instance.
$article = $articles->newEntity($this->request->data, [
'accessibleFields' => [
'topic' => true
]
]);
See also
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');
See also Cookbook > Helpers > FormHelper > Field Naming Conventions