2016-07-20 6 views
1

Post hasMany Comment와 Comment belongsTo Post로 링크 된 Post와 Comment라는 두 개의 모델이 있습니다. 처음 다섯 개의 주석이있는 모든 게시물을 가져 오려고합니다. 이 코드를 사용합니다 :Cakephp 3 - limit()와 포함 된 모델

$this->Posts->find('all') 
    ->contain([ 
     'Comments' => function($q) { 
      return $q 
       ->order('created ASC') 
       ->limit(5); 
} 
]); 

이 제한() 잘못 작동합니다. 이 문제를 해결하는 데 도움주세요. 포스트 컨트롤러에서

$this->hasOne('TopComments', [ 
    'className' => 'Comments', 
    'strategy' => 'select', 
    'conditions' => function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) { 
     $query->leftJoin(
      ['CommentsFilter' => 'comments'], 
      [ 
       'TopComments.post_id = CommentsFilter.post_id', 
       'TopComments.created < CommentsFilter.created' 
      ]); 
     return $exp->add(['CommentsFilter.id IS NULL']); 
    } 
]); 

: How to limit contained associations per record/group? 내가이 (포스트 모델)을 좋아하는 시도 : 나는이 예제를 사용

$this->Posts->find('all') 
    ->contain([ 
     'TopComments' => function($q) { 
      return $q 
       ->order('TopComments.created ASC') 
       ->limit(5); 
} 
]); 

불행하게도이 작동하지 않습니다. 내가 틀린 곳을 모른다.

+0

가능한 중복이

을 시도해야 [기록/그룹 별 연결을 포함 제한하는 방법?] (HTTP ://https://www.adobe.com/go/learn_detail.asp?hl=ko&answer=30241975/how-to-limit-contained-associations-per-record-group) – arilia

답변

1

당신은 당신의 컨트롤러에서 모델

$this->hasMany('Comments', [ 
    'foreignKey' => 'post_id' 
]); 

에서의

$this->Posts->find() 
    ->contain([ 
     'Comments' => function($q) { 
      return $q 
       ->order(['created' =>'ASC']) 
       ->limit(5); 
} 
]); 
+0

불행히도 작동하지 않습니다. CakePHP는 강력한 프레임 워크이지만 때로는 기본 작업이 제대로 작동하지 않는 경우가 있습니다. – lupi

+0

고마워, 너와 같은 시간이야. –