CakePHP 3 - 使用ajax删除关联数据

时间:2015-11-11 20:28:08

标签: javascript php ajax cakephp cakephp-3.0

帖子可以有多位作者。

我想添加使用Ajax在帖子中删除作者的可能性。

PostsAuthorsTable.php

$this->belongsTo('Users', [
    'className' => 'Users',
    'foreignKey'    => 'user_id',
    'joinType' => 'INNER'
]);

PostsTable.php

$this->hasMany('PostsAuthors', [ 'foreignKey' => 'post_id' ]);

PostsController.php

public function delete_author($authorID)
{
    $id = $_GET['authorID'];
    $this->Posts->PostsAuthors->delete($id);
    $this->autoRender = false;
}

查看:帖子> edit.ctp(JavaScript部分)

<?php $this->start('script'); ?>
<script>
    $(document).ready(function () { 
        $('.delete-author').on('click', function () {
            $.ajax({
                url: '<?= $this->Url->build(["action" => "delete_author"]) ?>',
                type: 'GET',
                data: { authorID: $(this).data('id') }
            });

            return false;
        });
    });
</script>
<?php $this->end(); ?>

查看:帖子&gt; edit.ctp(HTML部分)

<?php foreach ($post_authors as $post_author): ?>
<tr>
    <td><?= $post_author->user->name ?></td>
    <td class="text-center">
        <a href="#" class="delete-author text-danger" data-id="<?= $post_author->id ?>">
            <i class="icon-trash"></i>
        </a>
    </td>
</tr>
<?php endforeach; ?>

感谢您的帮助。 :)

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

<强> PostsController.php

public function delete_author($authorID)
{
    $id = $_GET['authorID'];
    $entity = $this->Posts->PostsAuthors->get($id);
    $this->Posts->PostsAuthors->delete($entity);
    $this->autoRender = false;
}