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.

hasMany doesn't return other table

Hello, as stated in the title i have two tables :

group_question AND question

question has a foreign key : id_group_question which points to the group_question_id

I then generated my models with phalcon-devtools and i have these two lines.

In GroupQuestion.php

$this->hasMany('id', 'Question', 'id_group_question', ['alias' => 'Question']); 

In Question.php

$this->belongsTo('id_group_question', 'GroupQuestion', 'id', ['alias' => 'GroupQuestion']); 

And when i do :

$group_questions = GroupQuestion::find();

echo count($group_questions); // Works good, return 4
echo count($group_questions->question); // return 0
echo count($group_questions->question[0]) // Doing this since in another post it's said that it doesn't return an arrray, but this doesn't work either

Not sure whats wrong here...


Ok if i use findFirst it returns stuff properly... how to get the same result with find() ?

edited Aug '16

Find returns resultset. It's something like an array of rows but as an object.

This $group_questions is array of objects. You have to iterate over them to get relation for each element.

Be it like that:

foreach ($group_questions as $item) {

or like that:



Even with that line i still cannot get anything out of the resultset, i tried :

echo count($group_questions->question[0]->question)

echo $group_questions->question[0]->question->text

Please carefuly read our answers and try again :)

edited Aug '16

It worked with :

Two foreach like this

foreach($group_questions as $gq)
  foreach($gq->question as $question)
  echo $question->text

But im going to send this data to the view. I want it look like an array, so i tried :


But no question inside the array again

Edit :
I tried GroupQuestion::find()->toArray() but it doesn't return the related models data..only the group_questions..

edited Aug '16

You need to use query builder. Find() doesn't know anything about your relations and is not joining anything until you access something with alias.


Ok thanks for help !