0
votes

I have the following database model.

Model1 hasMany Users
Model2 hasMany Users
Model3 hasMany Users

And one user can only belong to one Model. So the table user fields are the following:

id username password model1_id model2_id model3_id

I need to check in CakePHP User model that the three foreign keys cannot be NULL at the same time.

Which is the best way to solve that? Because I can't create any custom validation rules, validation rules was thought for validating one field. So How can I validate multiple fields and print the pertinent validation error.

2
Shouldn't this be declared inside your database? Or are you saying that they MUST belong to one and only one at the any given time?danhardman
I want to show an error in case NULL, NULL, NULL. That's it.Serginho
And what about 1, 2, NULL and 1, 2, 3, that's what @Mr.E is asking for. This multiple foreign key scheme is usually an indicator for poor database design. People might be able to give you a hint if you'd come up with a more real world example.ndm
Ok, I'll explain the context: For example, you want to create an application where you give access to shops, salespersons, and sellers. Earch one has a table filled with your information. Notice that you save diferent information if is shop, seller or salesman. And to access into you app you have to assign users for each type of user. So how would you create your database and how would you get the user profile?User can be seller, shop or salesperson. And take notice that one shop can be more than one user.Tell me a better design seller, shop or salesperson. Tell me a better design.Serginho
So users have 3 keys seller_id, shop_id an sales_id and 1 user can belong to one of 3 tables, and among 3 fields, the 3 can't be null.Serginho

2 Answers

0
votes
you should add this in your Model.
public $validate = array(
'fieldName1' => array(
    'rule' => 'ruleName',
    'required' => true,
    'allowEmpty' => false,
    'message' => 'Your Error Message'
    )
);

Cakephp Validation links

0
votes

Use Custom validations

public $validate = array(
'table1_id' => array(
    'rule' => array('custom_validation'),
    'required' => true,
    'allowEmpty' => false,
    'message' => 'Your Error Message'
    ),
'table2_id' => array(
    'rule' => array('custom_validation'),
    'required' => true,
    'allowEmpty' => false,
    'message' => 'Your Error Message'
    ),
'table2_id' => array(
    'rule' => array('custom_validation'),
    'required' => true,
    'allowEmpty' => false,
    'message' => 'Your Error Message'
    )
);

function custom_validation(){
    if( empty($this->data['table1_id']) && empty($this->data['table2_id']) && empty($this->data['table3_id']) ) {
       return false;
    }

      return true;
}