備忘録

個人的な試行錯誤のメモですので間違った情報が載っていたらごめんなさい。

CakePHP3(3.0.0-alpha1)のブログチュートリアルで記事にコメント機能を追加する

①comentsテーブルを作る

CREATE TABLE comments (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
body TEXT,
article_id int(10),
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);

INSERT INTO comments (title,body,article_idcreated)
VALUES ('test', 'comment', 1, NOW());


②CommentsTable.phpを作る

<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;


class CommentsTable extends Table {

	public function initialize(array $config) {
		$this->addBehavior('Timestamp');
	}

	public function validationDefault(Validator $validator) {
        $validator
            ->notEmpty('title')
            ->notEmpty('body');

        return $validator;
    }
}


③ArticleTable.phpでhasManyの設定

public function initialize(array $config) {
    $this->addBehavior('Timestamp');

    $this->hasMany('Comments', [
            'className' => 'Comments'
    ]);
}


④ArticlesController.phpを書き換える

public function view($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid article'));
        }

        //$article = $this->Articles->get($id);
        $article = $this->Articles->find('all')->contain(['Comments'])->where(['id'=>$id])->first();

        $this->set(compact('article'));
}


⑤view.ctpを書き換える(下記を追加)

<h1>Comment</h1>
<table>
 <tr>
 <th>Id</th>
 <th>Title</th>
 <th>Created</th>
 </tr>
 <?php foreach ($article->comments as $comment): ?>
 <tr>
 <td><?= $comment->id ?></td>
 <td><?= $comment->title ?></td>
 <td><?= $comment->created->format(DATE_RFC850) ?></td>
 </tr>
 <?php endforeach; ?>
</table>


【備考】
viewで呼び出すときは$article->Commentsじゃなくて$article->commentsみたい