Kohana ORM: Validate the $_belongs_to relationship exists

前提是你 提交于 2019-12-12 03:18:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!