I have the following models
class Post extends \Phalcon\Mvc\Model {
...
$this->hasMany('id', 'PostMedia', 'parent_id');
}
class PostMedia extends \Phalcon\Mvc\Model {
...
$this->belongsTo('parent_id', 'Post', 'id');
}
To get all related entries I do the following
Post::find(1)->postMedia;
But how do I get just the first model? The following code results in a Phalcon\Mvc\Model\Resultset\Simple
object, but I need the PostMedia object.
Post::find(1)->getPostMedia(['limit' => 1]);
There are getFirst()
, getLast()
and other useful methods in the Phalcon\Mvc\Model\Resultset\Simple
class. Also there is another problem in your code: Post::find(1)
returns resultset, not Post object, so the correct code to get first related object will look like this:
$first_media = Post::findFirst(1)->postMedia->getFirst();