Check if hasMany has been defined


I have two Models:

  • ModelA has an hasMany relationship to ModelB with alias ModelBs
  • ModelB has, of course, a belongsTo relationship to ModelA with alias ModelA

So, in my DB, table modelb has a foreign key called modelaid to table modela.

Every ModelA MUST have at least one ModelB.

When I create a new ModelA, how can I check if at least one ModelB has been defined?

I implemented the method beforeValidationOnCreate on ModelA where I perform this check. I don't need to check inside beforeValidation because inside ModelB I return false on method delete().

So, inside beforeValidationOnCreate() in ModelA I tried to check the following:

  • If $this->ModelBs is set ( isset() ) not empty: it doesn't work. ModelBs is always a Resultset\Simple.
  • if $this->ModelBs->count() is greater than 0: it always is (on create), even when a ModelB instance is passed.

How can I do that?

Thank you.



count or sizeof are the good way :

class ModelA extends \Phalcon\Mvc\Model{
    public function beforeValidationOnCreate(){
        return sizeof($this->ModelBs)>0;


count and sizeof always return 0 because the resultset doesn't contain any proper instance of any already existing model.


if you add an instance of ModelB in modelBs, count returns well 1, and creation is possible

$arrayOfBs=array(new ModelB());