Question

I have two models which have the following relationships:

class Model_User extends ORM
{
    protected $_has_many = array(
        'images' => array('model' => 'User_Image')
    );
}

class Model_User_Image extends ORM
{
    protected $_belongs_to = array(
        'usedvehicle' => array(),
    );
}

What would be the best way to restrict the number of User Images? I was thinking of setting the limit by declaring const MAX = 3 in the Model_User_Image class and then use this value to check against current number of images. Is there a way to limit it via the relationships or rules?

Was it helpful?

Solution

This problem can actually be solved using Kohana's rules-system like the following:

1 Add a validation rule to your Model_User_Image that affects the id of the parent. You can use the Model_User with a specified method max_no_images.

public function rules()
{
    return array(
        'user_id' => array(
            array( array('Model_User', 'max_no_images') ),//automatically use value of the field as parameter
        ),
    );
}

2 Change the Model_User in two ways. First of all you need a constant or other kind of variable to determine the maximum number of allowed images. Next you will need to define the max_no_images in which you check if the maximum number of images is already reached (if so, return false). It can easily be done via ORM but may be faster if you directly use queries.

public static function max_no_images($user_id)
{
    $number_of_children = ORM::factory('User', $user_id)->children->count_all();
    return ($number_of_children < Model_User::max_children);
 }

While the code posted here is not tested, I did so in a slightly different variation, so this method really works. Check out how they used a specified function from the same model for validation in the documentation


Another way cou can approach this problem is using SQL rules. I'm not gonna say much more, you would need to do a check for the number of images when inserting/updating an entry of images, so from the idea it is quite the same as the ORM approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top