0
0

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 1 year has passed since last update.

CakePHP5 主キーに「id」を使用しない 「id」以外の主キー

Posted at

別システムからの移行でCakeのルールに沿わないテーブル構造です。マスタ的なテーブルであるため、ルールに沿ってCakeの恩恵をうけるよりはそのままのテーブル構造で進める方がコストが少ないと判断しました。

cake bake のあと

Entityの_accessibleに追加

src/Model/Entity/Xxx.php
class XXX extends Entity
{
    protected array $_accessible = [
        'code' => true,  // ← 主キーカラム追加
        ...

Table の validator を追加

src/Model/Table/Xxx.php
public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->scalar('code')
            ->requirePresence('code', 'create')
            ->notEmptyString('code');

ビューに追加

templates/xxx/add.php
<?php
    echo $this->Form->control('code', ['type' => 'text']);

edit.php は編集しない。主キーは変更できない仕様にするのがよさそう。頑張るところじゃないね。

あと、アソシエーションの設定が必要になるかもsrc/Model/Table/XxxTable.php の initialize に hasManyの設定と、相手のTable.phpのinitialezeに belongsTo の設定と。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?