问题
I'm trying to get some validation setup for one of my ORM models.
I have 2 tables: parent and children. In the children table, there is a column called 'parent' whose value is the primary ID of a row in the parent table.
What I'm trying to do, is create a validation rule that checks the parent ID specified actually exists in the parent table.
Is there an easy way to do this?
回答1:
Well I did come up with one solution. I created a static method in my Model class that accepts an ID as a parameter and just checks if the row exists.
So my Model_Child has a rules function like so:
public function rules()
{
return array(
'parent' => array(
// will call Model_Parent::exists($value)
array(array('Model_Parent', 'exists'))
)
);
}
Then my Model_Parent has the following:
public static function exists($id) {
$results = DB::select('*')->from('parent')->where('id', '=', $id)->execute()->as_array();
if(count($results) == 0)
return FALSE;
else
return TRUE;
}
This is working for me. Is there is a more elegant or proper solution?
回答2:
In MySQL (since this question is tagged mysql) you define a foreign key relationship between parent and child table and leave that problem to the system.
来源:https://stackoverflow.com/questions/9574548/kohana-orm-validate-the-belongs-to-relationship-exists