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

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



4.5k

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

edited Aug '16
$group_questions[0]->question

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) {
    $item->question
}

or like that:

$group_questions[0]->question;
$group_questions[3]->question;


4.5k

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 :)



4.5k
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 :

$group_questions->setHydrateMode(Resultset::HYDRATE_ARRAYS);
print_r($group_questions);

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.



4.5k
Accepted
answer

Ok thanks for help !