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 member of comment?

I have 3 tables: Posts, Comments, Members.

There is a one-to-many relationship between Posts and Comments. There is a one-to-one relationship between Comments and Members. When I retrieve the posts from the ORM, it returns the comments too: $post->comments. How is it possible to return the member of the comment: $post->comment->member?



43.9k

If your relations are well defined, you can use the ORM just like you wrote it !

In your use case, I think that aliasing is needed

<?php

class Comments extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
       $this->hasOne('id', 'Members', 'comment_id',array('alias'=>'member'));
   }

}


10.4k

I have tried this and it still doesn't return anything related to Members.

class Posts extends Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->setSource('blog_posts');
        $this->hasMany('postId', 'Likes', 'postId');
        $this->hasMany('postId', 'Comments', 'postId');
    }

}

class Comments extends Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->setSource('blog_comments');
        $this->hasOne('memberId', 'Members', 'memberId', array('alias' => 'member'));
    }
}

class Members extends Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->setSource('blog_members');
        $this->belongsTo('memberId', 'Comments', 'memberId');
    }
}


43.9k

Are you sure of your first field in hasOne ? For me, it should be something like:

    public function initialize()
    {
        $this->setSource('blog_comments');
        $this->hasOne('commentId', 'Members', 'memberId', array('alias' => 'member'));
    }


10.4k

It uses foreign keys to reference other table, doesn't it? If that is the case it would be memberId.



43.9k
edited Jun '14

Have you test it ?

Here Customer has one address. Address has one City

Models

<?php
  class Customer extends \Phalcon\Mvc\Model
  {
    public $customer_id;
    public $store_id;
    public $first_name;
    public $address_id;

    public function initialize()
    {
        $this->hasOne('customer_id', 'Address', 'address_id', array('alias' => 'addresse'));
    }
}

class Address extends \Phalcon\Mvc\Model
{

    public $address_id;

    public $address1;

    public $address2;

    public $city_id;

    public $phone;

    public function initialize()
    {
        $this->hasOne('address_id', 'City', 'city_id', array('alias' => 'ville'));
    }

class City extends \Phalcon\Mvc\Model
{

    public $city_id;

    public $city;

}

in view:

echo $customer->addresse->phone;
echo $customer->addresse->ville->city;


10.4k
Accepted
answer

Wow, I am such an idiot. The reason it wasn't working was because I didn't even have a comment in the database. I appreciate your help though!