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

Must have atleast N number of Related Record

Hello Guys,

New Phalcon User Here.... I would like to know what method to count how many "unsaved" related Model is attached to Model. Example:

$parentModel = new Parent();
// Validate that $parentModel should have atleast 3 child models before saving. 
$parentModel->save();

This way:

if (count($parentModel->child) != 3) {
 throw new Exception("error");
}

Hello Andres... I appreciate your response... but unfortunately count($parent->child) doesn't show the number of child that has been attached to the parent. By the way.... in $parent->child = $childs, $childs is an array of newly created model (not yet saved to database).

This way:

if (count($parentModel->child) != 3) {
throw new Exception("error");
}

So why count() won't be able to count an array of newly created model (not yet saved to database) if it's a simple array?

Let me have a simple example of my problem.

$children = array( 
            new Child(),
            new Child(),
            new Child());
$parent = new Parent();
$parent->child = $children;
echo count($parent->child); // should return 3, but it returns 0 instead

... inside $parent's validate function
return count($this->child) >= 3;

You can see that I have no longer a reference to the children array but through $parent->child only. The problem is that $parent->child seems to not return the children array anymore. Upon successfully saving the $parent those children were also saved which is correct.

So why count() won't be able to count an array of newly created model (not yet saved to database) if it's a simple array?



512
Accepted
answer

I think I have the same problem like this one, but I dont know if this functionality has been provided right at this Phalcon version. https://forum.phalcon.io/discussion/919/-solved-kind-of-related-records-disappearing

edited Jul '15

Try doing it this way:

$parent->child = null;
$parent->child = $children;