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

get related records using the magic getters

I don't know why I cannot use the function getComments(), for one item has many comments. with the item id, I want all the comments of the id

bug:The method "getComments" doesn't exist on model "Items"...

Here is the nearly whole models, and the main part of the api

Comments.php

    <?php

    class Comments extends \Phalcon\Mvc\Model
    {
    /**
    * @var integer
    */
    public $id;

    /**
    * @var integer
    */
    public $item_id;

    public function initialize()
    {
    $this->belongsTo("item_id", "Items", "id");

    }
}

Items.php

<?php

    class Items extends \Phalcon\Mvc\Model
    {   
    /**
    * @var integer
    */
    public $id;

    public function initialize()
    {
    $this->hasMany("id", "Comments", "item_id");   
    }
     /**
     * Return the related "comments"
     *
     * @return \Comments[]
     */
    public function getComments()
    {
    return $this->getRelated('Comments', null);
    }

}

api.php

<?php

     use Phalcon\Mvc\Model;
    $application->get('/items/{id:[0-9]+}',function($id)use($application){ 

    $comments=$items->getComments();
    $data = array();
    foreach ($comments as $comment) {
    $data[] = array(
        'commentid' => $comment->id,
        'text' => $comment->text,
        'time_create' => $comment->time_create,
        'nick_name' =>$comment->nick_name
    );
    } 
    echo json_encode($data);
}
edited Jun '14

How do you obtain the Items object?

  use Phalcon\Mvc\Model;

  $application->get('/items/{id:[0-9]+}',function($id)use($application){ 
    ///
    //Missing some code here?
    ///

    $comments=$items->getComments();
    $data = array();
    foreach ($comments as $comment) {
      $data[] = array(
          'commentid' => $comment->id,
          'text' => $comment->text,
          'time_create' => $comment->time_create,
          'nick_name' =>$comment->nick_name
      );
    }
    echo json_encode($data);
  }


1.0k
edited Oct '14

Here is how I obtain the Items object

    $phql = "SELECT * FROM Items WHERE id = :id:";
    $items = $application->modelsManager->executeQuery($phql, array(
        'id' => $id
    ))->getFirst();