0

I am new to Cakephp 3.0 and i don't know how to get all the products of the contracts in my example.

http://hpics.li/d2568a6

Models :

SalesContracts:

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class SalesContractsTable extends Table
{

    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');
        $this->table('sales_contracts');

        $this->belongsToMany('SalesProducts',[
            'className' => 'SalesProducts',
            'type' => 'INNER',
            'joinTable' => 'sales_contracts_products',
            'foreignKey' => 'sales_contracts_id',
            'targetForeignKey' => 'sales_products_id'
        ]);
    }
}

SalesProducts:

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class SalesProductsTable extends Table
{

    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');
        $this->table('sales_products');

        $this->belongsToMany('SalesContracts',[
            'className' => 'SalesContracts',
            'joinTable' => 'sales_contracts_products',
            'type' => 'INNER',
            'foreignKey' => 'sales_products_id',
            'targetForeignKey' => 'sales_contracts_id'
        ]);
    }
}

This method receives the ID of the contract in parameter and I need to use it to get his products.

    public function show_products($id = null){
 $products $this->SalesContracts->find('all')->contain(['SalesProducts'])->where(['SalesContractsProducts.sales_contracts_id' => $id]);

    }

But I cannot write a proper query about that..

Any solutions ?

Thanks for your help!

ndm
  • 59,784
  • 9
  • 71
  • 110
  • possible duplicate of [find on associated model's condition CakePHP 3.0](http://stackoverflow.com/questions/26799094/find-on-associated-models-condition-cakephp-3-0) – ndm Dec 15 '14 at 09:16
  • Using matching() doesn't make it work :( – Ducrey Romaric Dec 15 '14 at 09:32
  • I kinda misread your code, even tough matching is an option and would work just fine (and if it doesn't work show what you've tried, "_doesn't work_" is never a proper problem descrption), you could also use a proper `where` condition to match the sales contracts id (ie do not match on the join table, it doesn't make any sense in that form anyways). – ndm Dec 15 '14 at 10:11
  • I've triied like this: $products = $this->SalesContracts->find()->matching('SalesProducts', function($id,$q) { return $q->where(['sales_contracts_id' => $id]); }); – Ducrey Romaric Dec 15 '14 at 10:27
  • It works using a proper way to do it – Ducrey Romaric Dec 15 '14 at 15:18

0 Answers0