Hello,
I am struggling in getting my first table relations working in Phalcon.
Studying the model relations in the documentation I've put together my first relations:
Topic model:
public function initialize()
{
$this->hasMany('id', 'Multiple\Forums\Models\Post', 'topic_id');
$this->belongsTo('category_id', 'Multiple\Forums\Models\Category', 'id', array('foreignKey' => true));
$this->hasMany('id', 'Multiple\Forums\Models\TopicViews', 'topic_id');
}
Post model:
public function initialize()
{
$this->belongsTo('topic_id', 'Multiple\Forums\Models\Topic', 'id', array('foreignKey' => true));
$this->belongsTo('user_id', 'Multiple\Forums\Models\User', 'id', array('foreignKey' => true));
}
All the models are correctly in the Multiple\Forums\Models
namespace.
The relation itself:
- A topic can have many posts as well as have many views (view counter)
- A topic belongs to a forum category under which the topic is listed
- A post belongs to a single topic and a single user
Now I have a function called getParticipants
in my Topic model which gets the users that have taken part in the topic conversation (posts):
public function getParticipants()
{
$users = array();
foreach($this->post as $post){
$users[$post->user->id] = array(
'last' => false,
'image' => $post->user->userDetails->image == null ? 'img/user/defaults/'.rand(1, 20).'.png' : $post->user->userDetails->image,
'username' => $post->user->username
);
}
$latest = Post::findFirst("topic_id = ".$this->id, array(
'order' => 'created_timestamp DESC'
));
$users[$latest->user->id]['last'] = true;
return $users;
}
I think I'm doign the relations wrong because when I do $this->post
, which should get me all the posts that belong to that topic, but instead I get
Notice: Access to undefined property Multiple\Forums\Models\Topic::post
I would really appreciate if someone could explain me how the model/table relation are supposed to properly work.
Thank-you in advance.