Mysql
 sql >> Datenbank >  >> RDS >> Mysql

CakePHP - Effizientes Durchsuchen von 3 Tabellen mit JOIN

Ich bevorzuge weniger Code mit Kuchenmodell/Tabellennamenskonvention (db table products - Modellname Product , db-Tabelle prices - Modellname Price ) für das weitere Projektmanagement. Es sieht so aus, als ob Sie Folgendes tun möchten:

$results = $this->Product->find('all', array(
    'fields' => array(
        'Company.name',
        'Product.feature',
        'Price.price'
    ),
    'joins' => array(
        'LEFT JOIN companies AS Company ON Product.company_id = Company.id
         LEFT JOIN prices AS Price ON Product.id = Price.product_id'
    ),
    'conditions' => array(
        'Company.name LIKE' => '%'.$search_term.'%',
        'Product.feature' => $product_feature,
        'Price.price <' => $price
    ),

 ));

sondern wenn Sie möchten Produkte mit erhalten Ihre alle Kriterien (Firma und Preis) nur , Sie sollten INNER JOIN verwenden , und GROUP BY Produkt (group Option).

Wenn Sie alle Produkte mit vielen Preisen und Firmenergebnissen erhalten möchten und Sie Modellbeziehungen festlegen/verknüpfen, können Sie contain verwenden Option, wie:

$contain = array(
    'Company' => array(
        // ...
        'conditions' => array('Company.name LIKE' => '%'.$search_term.'%'),
        // ...
    ),
    'Price' => array(
        // you can set: 'fields' => array('id', ...),
        'conditions' => array('Price.price <' => $price),
        // you can set order: 'ordder' => '....'                
    )
);

$this->Product->attach('Containable');
$post = $this->Product->find('all', array(
    // ...
    'contain' => $contain,
    'conditions' => array('Product.feature' => $product_feature),
    // ...
)); 

Sie erhalten also alle Produkte mit feature => $product_feautre , und Sie erhalten LEFT JOIN Firmen und Preise zu diesen Produkten.

Hoffe das hilft.