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


CakePHP 3 - Deleting associated data using ajax

文章可以有多个作者。

我想添加使用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;
}

查看:Posts>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(); ?>

查看:文章>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; ?>

谢谢你的帮助。:)

我找到了解决方案。

PostsController.php

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