【问题标题】:cakephp: how to use find statements in models instead of controllercakephp:如何在模型中使用 find 语句而不是控制器
【发布时间】:2012-01-03 14:30:35
【问题描述】:

我读到了“胖模型和瘦控制器”的概念。我当然想遵循这个概念。

现在,我所有的控制器都很胖,我的模型很瘦。我在控制器中有很多 find stmts(查询),我想将它们移到模型中。但我不知道该怎么做。

我应该在模型的哪个函数中放置 find 语句?在模型中设置 stmts 之后,我是否可以自动在相应视图中查看该数据?

谁能给我一个例子?我已经浏览了 cakephp 食谱博客示例。在那里,find stmts 在控制器而不是模型中。该模型仅包含关系和验证。我还没有看到包含 find stmts 的模型示例。

【问题讨论】:

    标签: cakephp model find


    【解决方案1】:

    你的模型上可以有这样的东西

    function getProductGroups($company_id){
    
        $product_groups = $this->find('all', 
                    array('conditions' => array('ProductGroup.company_id' => $company_id) )
                );
        return $product_groups;
    }   
    

    *这样您也可以将 find 语句用于其他控制器。

    【讨论】:

      【解决方案2】:

      要在模型中使用 find,你可以写:

      //在用户模型中 $this->find('first', array('recursive' => '-1', 'conditions' => array('User.id' => $userId), 'fields' => $this->authFields ));

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        已给出答案的答案是您问题的一部分。您可以在没有 Model 类声明的情况下使用 find 方法(所以 $this->find() 而不是 $this->Model->find())。

        为了遵守“胖模型,瘦控制器”原则,您的模型应该包含应用程序的大部分业务逻辑,而控制器则处理您的视图使用的模型中的数据。

        因此,如果您想让所有 find 逻辑发生在您的模型中,您应该执行以下操作。

        产品.php:

        <?php
          class ProductModel extends AppModel {
            //Associations, etc. go here
        
            function getProducts($limit=5) {
              $products = array();
              $products = $this->find('all', array('limit' => $limit));
              return $products;
            }
          }
        ?>
        

        注意你不能在你的模型中使用$this-&gt;set(),你应该在你的控制器中使用它:

        ProductsController.php:

        <?php
          class ProductsController extends AppController {
            //Components, helpers, etc. go here
        
            function index() {
              $products = $this->Product->getProducts(10);
              $this->set('products', $products);
            }
          }
        ?>
        

        现在您可以查看已填充的$products 变量(如果相关数据库表中有记录)。

        This is a great article 详细介绍了 Cake 的概念,MVC in general 上的 Cookbook 中还有另一个。

        【讨论】:

        • mensch,非常感谢您的精彩解释和链接。我是否能够通过产品模型查找获得所有相关的模型数据。 IE。如果 Product hasOne Manufacturer 和 Product hasMany Customer,我可以通过 Product 模型的 find 获取 Manufacturer 和 Product 数据吗?
        • mensch,太好了,我尝试了一个简单的测试项目,是的,我能够在视图中获取相关模型的数据。再次感谢。
        • 很高兴听到!您确实可以通过将recursive 设置为高于0 的值,或者通过访问这样的find 方法来访问您的关联数据:$this-&gt;Customer-&gt;find()
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多