Help us understand the problem. What is going on with this article?

CakePHP3 リレーション関係にあるテーブルに対してバリデーションを掛けたい

前提

  • PHP
    • 7.3.11
  • CakePHP
    • v3.6.14
  • MySQL
    • 5.7.26

0. テーブル構造

mysql> desc users;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| name          | varchar(255) | NO   |     | NULL    |                |
| tel           | varchar(255) | NO   |     | NULL    |                |
| email         | varchar(255) | NO   | MUL | NULL    |                |
| created       | datetime     | NO   |     | NULL    |                |
| modified      | datetime     | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+
19 rows in set (0.00 sec)

mysql> desc addresses;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| user_id       | int(11)      | NO   |     | NULL    |                |
| city          | varchar(255) | NO   |     | NULL    |                |
| building      | varchar(255) | NO   | MUL | NULL    |                |
| created       | datetime     | NO   |     | NULL    |                |
| modified      | datetime     | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+
19 rows in set (0.00 sec)

1. 保存したいデータ

  • リレーション関係のような階層構造を持った連想配列にする
$data = [
    'user' => [
        'email' => 'hoge@example.com',
        'tel' => '09012345678',
        'name' => '山田太郎',
        'address' => [
            'city' => '2200011',
            'building' => '14',
            'address' => '横浜市西区高島',
            'building' => '123'
        ],
    ],
];

2. バリデーション

  • リレーション関係のような階層構造を持った連想配列にする
$validate = [
    'associated' => [
        'Addresses' => [
            'validate' => 'default',
        ],
    ],
];

バリデーションクラス

/**
 * Default validation rules.
 *
 * @param \Cake\Validation\Validator $validator Validator instance.
 * @return \Cake\Validation\Validator
 */
public function validationDefault(Validator $validator)
{
    $validator->notEmpty('city');
    $validator->notEmpty('building');

    return $validator;
}

3. オブジェクト生成

  • 第一引数に保存したいデータを、第二引数にバリデーションを渡す
$user = $this->Users->newEntity($data, $validate);

4. エラー検知

  • バリデーションエラーに引っかかってる場合、以下のメソッドでエラー内容を取得することが可能
    • EntityTrait::getError() or EntityTrait::getErrors()
tatsuo-iriyama
Web Engineer|96'|高卒|前職:溶接工|2019-01〜ユアマイスター株式会社|
yourmystar
サービス産業のIT化プラットフォーム「ユアマイスター」と大切なものをもっと大切にするメディア「ユアマイスター スタイル」を運営するスタートアップです。
http://corp.yourmystar.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした