Cakephp フレームワークで CMS を構築しました。すべてではなく 1 つまたは複数のタグを削除できるので、投稿からすべてのタグを削除するにはどうすればよいですか。次のファイルがあります。
ポストモデル:
<?php
public $displayField = 'title';
public $hasAndBelongsToMany = array(
'Tag' => array(
'className' => 'Tag',
'joinTable' => 'posts_tags',
'foreignKey' => 'post_id',
'associationForeignKey' => 'tag_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => '',
)
);
?>
タグ モデル:
<?php
public $displayField = 'name';
/**
* hasAndBelongsToMany associations
*
* @var array
*/
public $hasAndBelongsToMany = array(
'Post' => array(
'className' => 'Post',
'joinTable' => 'posts_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'post_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
?>
ポストコントローラー:
<?php
public function admin_edit($id = null) {
$this->Post->id = $id;
if (!$this->Post->exists()) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$tags = explode(',', $this->request->data['Post']['tags']);
foreach ($tags as $_tag) {
$_tag = strtolower(trim($_tag));
if ($_tag) {
$this->Post->Tag->recursive = -1;
$tag = $this->Post->Tag->findByName($_tag);
if (!$tag) {
$this->Post->Tag->create();
$tag = $this->Post->Tag->save(array('name' => $_tag, 'slug' => $_tag));
$tag['Tag']['id'] = $this->Post->Tag->id;
if (!$tag) {
$this->_flash(__(sprintf('The Tag %s could not be saved.', $_tag), true), 'success');
}
}
if ($tag) {
$this->request->data['Tag']['Tag'][$tag['Tag']['id']] = $tag['Tag']['id'];
}
}
}
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('The post has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The post could not be saved. Please, try again.'));
}
} else {
if (empty($this->request->data)) {
$this->request->data = $this->Post->read(null, $id);
$tags = array();
if (isset($this->request->data['Tag']) && !empty($this->request->data['Tag'])) {
foreach ($this->request->data['Tag'] as $tag) {
$tags[] = $tag['name'];
}
$this->request->data['Post']['tags'] = implode(', ', $tags);
}
}
}
}
?>
admin_edit.ctp:
echo $this->Form->create('Post');
echo __('Admin Edit Post');
echo $this->Form->input('id');
echo $this->Form->input('user_id');
echo $this->Form->input('title');
echo $this->Form->input('slug');
echo $this->Form->input('content');
echo $this->Form->input('excerpt');
echo $this->Form->input('status');
echo $this->Form->input('comment_status');
echo $this->Form->input('comment_count');
echo $this->Form->input('type');
echo $this->Form->input('Category');
echo $this->Form->input('Post.tags');
echo $this->Form->end(__('Submit'));
お手伝いありがとう。