如果实体有关系,CakePHP 3.x自定义验证

Trying to get my head around some slightly more complex custom CakePHP validation rules.

I have Posts that have to be associated with a City Some (larger) cities have SubCities. My Posts table has both city_id and sub_city_id, so in some cases, sub_city_id will be Null.

I have a nice ajax form working that loads and lets you select a SubCity if you've first selected a City that has some. I would like to write a validation rule so you can't have a sub_city_id of Null if SubCities are available on the city_id field.

Any help on the best way to go about this?

Did you try to check the manual? Read about Conditional validation

When defining validation rules, you can use the on key to define when a validation rule should be applied. If left undefined, the rule will always be applied. Other valid values are create and update. Using one of these values will make the rule apply to only create or update operations.

Additionally, you can provide a callable function that will determine whether or not a particular rule should be applied:

$validator->add('picture', 'file', [
    'rule' => ['mimeType', ['image/jpeg', 'image/png']],
    'on' => function ($context) {
        return !empty($context['data']['show_profile_picture']);
    }
]);

↑ This example is taken from the book. So modify it to your needs. Inside the callback put your logic for checking the cities.