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

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?


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; ?>


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