【问题标题】:Adding a comment to an article in CakePHP 3在 CakePHP 3 中为文章添加评论
【发布时间】:2016-08-08 15:06:29
【问题描述】:

我正在尝试向现有文章添加新评论,我尝试了几乎所有可能的方式来添加新评论,但没有找到任何可行的方法,请发布,如果有人知道如何完成此操作。

我还尝试了 cakephp 3 文档中提到的所有示例

保存关联 -> http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-associations

$newData = [ 'title' => 'test', 'body' => 'test body', 'author_name' => 'test', 'author_url' => 'author_url', 'author_email' => 'author_email' ];
        $newData[ 'Posts' ] = [ '_ids' => [ 1 ] ];

        print_r( $newData );

        $tagEntity = $this->Posts->Comments->newEntity();
        $tag = $this->Posts->Comments->patchEntity( $tagEntity, $newData );

        print_r( $tagEntity );
        print_r( $tag );

        if( $this->Posts->Comments->save( $tag ) ) {

        }

结果是

Array
(
    [title] => sdsds
    [body] => dsfsf
    [author_name] => ss
    [author_url] => author_url
    [author_email] => author_email
    [Posts] => Array
        (
            [_ids] => Array
                (
                    [0] => 1
                )

        )

)
Blog\Model\Entity\Comment Object
(
    [title] => sdsds
    [body] => dsfsf
    [author_name] => ss
    [author_url] => author_url
    [author_email] => author_email
    [Posts] => Array
        (
            [_ids] => Array
                (
                    [0] => 1
                )

        )

    [[new]] => 1
    [[accessible]] => Array
        (
            [*] => 1
        )

    [[dirty]] => Array
        (
            [title] => 1
            [body] => 1
            [author_name] => 1
            [author_url] => 1
            [author_email] => 1
            [Posts] => 1
        )

    [[original]] => Array
        (
        )

    [[virtual]] => Array
        (
        )

    [[errors]] => Array
        (
        )

    [[invalid]] => Array
        (
        )

    [[repository]] => Blog.Comments
)

【问题讨论】:

  • 为什么你不尝试通过 CommentsController 添加评论并通过 $post_id 来添加功能?

标签: cakephp cakephp-3.0


【解决方案1】:

终于搞定了

$data = $this->request->data;
$data[ 'posts' ] = ['_ids' => [ $post->id ] ];
$comment = $this->Posts->Comments->patchEntity( $this->Posts->Comments->newEntity(), $data, [ 'Posts' ] );
$this->Posts->Comments->save( $comment );

if( $this->Posts->save( $comment ) ) {
    echo 'done';
} else {
    print_r( $comment );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2021-01-07
    • 2019-01-26
    • 2017-12-16
    • 2021-08-04
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多