multiplle levels of relation ship

Hello,

I have a model with two relations:

$this->hasMany(
            'objectKey',
            CatalogArticle::class,
            'parentKey',
            ['alias' => 'subArticles']
        );

$this->belongsTo(
            'objectKey',
            Object::class,
            'id',
            ['alias' => 'object']
        );      

in the model the primaryKey is ObjectKey and I also have a status field with -1 or 1.

I want to have the count of subArticles with status >0 using relations for a given objectKey value

I could have

$nbSubArticles = count(CatalogArticle::findFirstByObjectKey(41)->subArticles); 

but this gives me even those with status = -1, I don't want them.

Any idea? I don't want to create a custom query for that, i would use the relation and models.



7.5k

you can make as many as you like with different aliases

phalcon 3.4 Conditionals

phalcon 4.x Conditionals

$this->hasMany(
    'objectKey',
    CatalogArticle::class,
    'parentKey',
    [
        'alias' => 'subArticles',
        'params' => [
            'conditions' => 'status > 0'
        ]
    ]
);

I believe you can include a conditional when querying for related models.

Something like:

$Object = Model::findFirst($objectKey);
$subArticles = $Object->getRelated('subarticles',['status > 0']);
edited May '20

Thanks for the suggestions I think i can mix both of your responses to have something as I would.

I can use the relation on Object model indeed to add an alias subArticles with a parameter on the parentKey = objectKey field of the CatalogArticle model.

Then use the findFirst on the Object model with status > 0 in the condition and then use the relation subArticles with status >0 params, there i will be able to do a count on the given results.

Thanks a lot for both of you, i will test that and confirm the results.