duanhe1965 2014-08-18 10:37
浏览 70
已采纳

Phalcon:如何以1-n关系获得第一个模型

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]);
  • 写回答

1条回答 默认 最新

  • drzrzzkh462254 2014-08-18 14:01
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?