Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

hasManyToMany relation with additional condition

Is there an option to add additional conditions to wizard function hasManyToMany? I've checked the docs but they do not list all possible options for hasManyToMany (alias and foreginKey are only listed). If this cannot be done with hasManyToMany, is there any other option available - eg. retrieve all and then filter on some model load event?

Simple example: I have 3 tables Group, Relation and User, and would like use Relation table to create two properties in User model - activegroups and inactivegroups.

Code:

class GroupModel extends Model {
    public $id;    
    public $name;
}

class RelationModel extends Model {
    public $id;    
    public $related_id_one;
    public $related_id_two;
    public $active;
}

class UserModel extends Model {

    public function initialize() {

        $this->hasManyToMany(
            "id",
            "RelationModel",
            "related_id_one",
            "related_id_two",
            "GroupModel",
            "id",
            array(  'alias' => 'active_groups', 
                    'conditions' => 'RelationModel.active = true')
        );

        $this->hasManyToMany(
            "id",
            "RelationModel",
            "related_id_one",
            "related_id_two",
            "GroupModel",
            "id",
            array(  'alias' => 'inactive_groups', 
                    'conditions' => 'RelationModel.active = false')
        );
    }
}

Tnx!

And pls note that I asked the same question on stackoverflow



4.0k
Accepted
answer

You would have to call the conditions when you actually create the query.

class GroupModel extends Model {
    public $id;    
    public $name;
}

class RelationModel extends Model {
    public $id;    
    public $related_id_one;
    public $related_id_two;
    public $active;
}

class UserModel extends Model {

    public function initialize() {

        $this->hasManyToMany(
            "id",
            "RelationModel",
            "related_id_one",
            "related_id_two",
            "GroupModel",
            "id",
            array(  'alias' => 'UserGroups' )
        );

    }
}

$user = UserModel::findFirst();
$active_groups = $user->getUserGroups(['conditions' => 'RelationModel.active = true']);
$inactive_groups = $user->getUserGroups(['conditions' => 'RelationModel.active = false']);

Hopefully that'll get you in the right direction.