簡體   English   中英

CakePHP查找具有相關模型條件的列表

[英]CakePHP find list with related model conditions

我正在嘗試獲取ID列表(la find('list') ),但無法弄清楚如何使用相關的模型條件。

我的協會是: Product hasAndBelongsToMany Category Product belongsTo Manufacturer

我想查找類別ID列表中的產品ID列表,並且具有某個制造商seo_url。 我已經嘗試了大量的包含條件,引用其他模型的條件,甚至嘗試使用find('all')來查看我的條件是否可行,但無法獲得任何結果。

我設法使用Product-> query()得到一個,但它不是列表的格式。 我可以遍歷數組並獲取ID或其他任何內容,但感覺非常糟糕。 我想確保Cake仍然對我的查詢進行所有安全檢查,以及其他任何自動化操作。 這是我工作的查詢:

$all_results = $return['Category']['all_results'] = $this->Product->query('
    SELECT `Product`.`id`
        FROM `categories_products` as `CategoriesProduct`
        JOIN `products` as `Product` ON (`CategoriesProduct`.`product_id` = `Product`.`id`)
        JOIN `manufacturers` as `Manufacturer` ON (`Product`.`manufacturer_id` = `Manufacturer`.`id` AND `Manufacturer`.`seo_url` = \''.$manufacturer.'\')
        WHERE `CategoriesProduct`.`category_id` IN ('.implode(',', $search_categories).')
');

這回來了

[all_results] => Array
    (
         [0] => Array
            (
                [Product] => Array
                    (
                        [id] => 101787
                    )

            )

        [1] => Array
            (
                [Product] => Array
                    (
                        [id] => 100781
                    )

            )

        [2] => Array
            (
                [Product] => Array
                    (
                        [id] => 101887
                    )

            )

        [3] => Array
            (
                [Product] => Array
                    (
                        [id] => 101888
                    )

            )

    )

注意: $search_categories是類別ID的列表(即: array(12,42,24,5)

CakePHP對於相關模型的conditions可能很奇怪。 特別是與HABTM的關系。 即使將recursive設置為最高值(即2)。 查看文檔以獲取有關HABTM的更多詳細信息。

請嘗試以下方法。 雖然從上面來看,我認為它不會起作用:

$conditions = array('Category.id' => $category_ids, 'Manufacturer.seo_url' => $manufacturer);
$this->Product('list', array('recursive' => 1, 'conditions' => $conditions));

另外,盡可能避免使用query() MVC的重點是將數據顯示邏輯隔離開來。 使用query()類的東西就是打破了。

您想要的結果的問題是,如果您在相關模型上使用條件,Cake將不會返回剝離結果數組。

發生這種情況是因為Cake只會在您的相關模型上使用這些條件,並在相關模型的條件為真的情況下返回結果。

如果您想要獲得僅具有特定類別的產品,則需要通過類別模型進行查詢,因為這樣您就可以使用產品上的條件。 這看起來像這樣:

$this->Category->find('all', array('conditions' => array('Category.id' => 2));

這將只返回所需類別及其相關產品。 但是,如果您需要列表,這不是很令人滿意,因為您必須手動執行轉換。

我寧願看一下Linkable Plugin ,它可以提供你想要的功能,因為它像你在查詢中一樣使用連接擴展了Cake。 這樣就可以在相關模型上獲得具有條件的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM