问题描述
我正在尝试为我的一个ORM模型获得一些验证设置.
I'm trying to get some validation setup for one of my ORM models.
我有2张桌子:父母和孩子.子表中有一个名为"parent"的列,其值是父表中行的主要ID.
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.
我要做的是创建一个验证规则,以检查指定的父ID在父表中是否实际存在.
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?
推荐答案
我确实提出了一种解决方案.我在Model类中创建了一个静态方法,该方法接受一个ID作为参数,并仅检查行是否存在.
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_Child具有如下规则函数:
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'))
)
);
}
然后我的Model_Parent具有以下内容:
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?
这篇关于Kohana ORM:验证$ _belongs_to关系是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!