2016-08-17 9 views
0

私はCakePHP 3.2で作業しています。CakePHP:同じ値を2回印刷するクエリ

私はcategoriesproductsseller_productsテーブルとの関連付けが

categories->hasMany('Products'); 
seller_products->hasMany('Products'); 

ありきseller_products.stock> 0

は、これは私が

をやっているここで私は、カテゴリ別にすべての製品グループを取得する必要が
$pros1 = $this->Products->Categories->find() 
      ->where([ 
      'Categories.status' => 0, 
      ]) 
      ->contain([ 
      'Products.SellerProducts', 'Subcategories', 'Subcategories.ProductTypes' 
      ]) 
      ->matching('Products.SellerProducts', function(\Cake\ORM\Query $q) { 
      return $q->where(['SellerProducts.stock >' => 0]); 
      }); 

しかし、デバッグ時には同じ値を2回返します。 foreach($pros1 as $p){debug($p);}が同じ値を二回

/src/Controller/PagesController.php (line 120) 

object(App\Model\Entity\Category) { 

    'id' => (int) 1, 
    'title' => 'Electronics', 
    'description' => '', 
    'icon' => 'fa-television', 
    'status' => (int) 0, 
    'created' => object(Cake\I18n\Time) { 
     ......... 
    } 

/src/Controller/PagesController.php (line 120) 

object(App\Model\Entity\Category) { 

    'id' => (int) 1, 
    'title' => 'Electronics', 
    'description' => '', 
    'icon' => 'fa-television', 
    'status' => (int) 0, 
    'created' => object(Cake\I18n\Time) { 
     ......... 
    } 

debug(count($pros1))プリントドキュメントから1

答えて

1

引用印刷されています。INNER JOINを作成します。この機能として

を、あなたは が上distinctを呼び出して検討する必要があります の条件で既に条件が除外されていない場合は、重複行が表示される可能性があります。たとえば、同じユーザーが単一の の記事で複数回コメントする場合、 の場合があります。あなたのケースでは

Cookbook > Database Access & ORM > Query Builder > Filtering by Associated Data

同じカテゴリに属する​​複数の一致製品があります。したがって、テーブルのプライマリキーには別個のselectを使用するか、それによってグループ化してください(there may be no difference between the two)。

$pros1 = $this->Products->Categories 
    ->find() 
    ->distinct('Categories.id') 
    // ... 
// ... 
    ->matching(/* ... */) 
    ->group('Categories.id'); 

も参照してください

+0

ありがとうございました。マッチングは機能しません。それはまだ 'SellerProducts.stock = 0'で製品を表示しています –

+0

@AnujTBEこれは別の質問です。それはマッチングの仕方ではありません。 Matchingフィルタは親レコードをフィルタリングします。子レコード( 'SellerProducts')が含まれていて、特定のレコードのみを必要とする場合は、それらもフィルタリングする必要があります。 ** http://stackoverflow.com/a/26800203/1392379**を参照してください。 – ndm

関連する問題