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.

Can you say me more about models relations in Phalcon (hasOne, hasMany...)

For example, I have a "Users" model (table) like this (simplified):

class Users extends Model
{
    public $id;
    public $name;
}

and the "Posts" model:

class Posts extends Model
{
    public $id;
    public $title;
    public $description;
    public $uid; // "uid" contains an id from the "Users" table.

    // This is the my variant and I don't understand how can I get this, help))
    public function initialize()
    {
        $this->hasOne('uid', 'Users', 'id');
    }
}

I want to connect this tables and get the name from Users by uid from Posts (id == uid). How can I do it and get from controller?



994
Accepted
answer

Add an alias to the hasOne like this:

$this->hasOne('uid', 'Users', 'id', array('alias' => 'user'));

In your view, when you have something like this:

My Posts:

<?php foreach ($posts as $post): ?>
    Title: <?php echo $post->title; ?><br />
    User: <?php echo $post->user->name; ?><br />
    Description:<br />
    <?php echo $post->description; ?><br />
    <hr />
<?php endforeach; ?>


4.8k

Everything works perfectly! Thank you very much! Good luck to you:)