We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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 - active_groups and inactive_groups.

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



5.7k
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.