[英]Kohana ORM: Validate the $_belongs_to relationship exists
I'm trying to get some validation setup for one of my ORM models. 我正在尝试为我的一个ORM模型获得一些验证设置。
I have 2 tables: parent and children. 我有2张桌子:父母和孩子。 In the children table, there is a column called 'parent' whose value is the primary ID of a row in the parent table.
在子表中,有一个名为“ parent”的列,其值是父表中一行的主ID。
What I'm trying to do, is create a validation rule that checks the parent ID specified actually exists in the parent table. 我正在尝试做的是创建一个验证规则,该规则检查指定的父ID在父表中是否实际存在。
Is there an easy way to do this? 是否有捷径可寻?
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.
我在Model类中创建了一个静态方法,该方法接受一个ID作为参数,并仅检查该行是否存在。
So my Model_Child has a rules function like so: 所以我的Model_Child具有如下规则函数:
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: 然后我的Model_Parent具有以下内容:
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?
有没有更优雅或更合适的解决方案?
在MySQL中(由于该问题被标记为mysql),您定义了父表和子表之间的外键关系,并将该问题留给系统。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.