8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3でエンティティクラスを任意のクラスにする

Last updated at Posted at 2014-10-28

予約語と被ってしまった場合など。

listsというテーブルがありモデルをbakeした。

<?php
namespace App\Model\Table;

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

/**
 * Lists Model
 */
class ListsTable extends Table {

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
	public function initialize(array $config) {
		$this->table('lists');
		$this->displayField('name');
		$this->primaryKey('id');

		$this->hasMany('Tasks', [
			'foreignKey' => 'list_id',
		]);
	}

/**
 * Default validation rules.
 *
 * @param \Cake\Validation\Validator $validator
 * @return \Cake\Validation\Validator
 */
	public function validationDefault(Validator $validator) {
		$validator
			->add('id', 'valid', ['rule' => 'numeric'])
			->allowEmpty('id', 'create')
			->allowEmpty('name')
			->add('created_at', 'valid', ['rule' => 'datetime'])
			->validatePresence('created_at', 'create')
			->notEmpty('created_at')
			->add('updated_at', 'valid', ['rule' => 'datetime'])
			->validatePresence('updated_at', 'create')
			->notEmpty('updated_at');

		return $validator;
	}

}

問題はエンティティクラス

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * List Entity.
 */
class List extends Entity {

/**
 * Fields that can be mass assigned using newEntity() or patchEntity().
 *
 * @var array
 */
	protected $_accessible = [
		'name' => true,
		'created_at' => true,
		'updated_at' => true,
		'tasks' => true,
	];

}

ListだとどうにもならないのでListObjectと改名する。

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * ListObject Entity.
 */
class ListObject extends Entity {

/**
 * Fields that can be mass assigned using newEntity() or patchEntity().
 *
 * @var array
 */
	protected $_accessible = [
		'name' => true,
		'created_at' => true,
		'updated_at' => true,
		'tasks' => true,
	];

}

ListTableクラスが使うエンティティを切り替える。

具体的にはinitilizeに1行追加する。

	public function initialize(array $config) {
		$this->table('lists');
		$this->displayField('name');
		$this->primaryKey('id');

		$this->hasMany('Tasks', [
			'foreignKey' => 'list_id',
		]);

        $this->entityClass('App\Model\Entity\ListObject');
	}
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?