【问题标题】:CakePHP: Best practices for associating small, "choice" tablesCakePHP:关联小型“选择”表的最佳实践
【发布时间】:2013-01-06 09:30:14
【问题描述】:

快速最佳实践问题。

我的关联如下: 用户拥有一个用户基本信息
UserBasicInfo 有一个国家(用户居住的国家)的选择元素。
选择元素由一个简单的“国家”表(id、国家名称、缩写)填充

最好使用 Model::query() 从国家表中获取数据吗?或者我应该为这些数据创建一个模型?

如果创建模型,我应该使用与 UserBasicInfo 模型的关联,还是应该只使用 $uses 变量?

如果它影响答案,实际上有许多选择字段以类似的方式填充。

【问题讨论】:

    标签: cakephp foreign-keys cakephp-model


    【解决方案1】:

    如果它影响答案,实际上有许多选择字段以类似的方式填充。

    可能。您是否有多个国家/地区选择框,或者这些选择字段都是从不同的表中提取的?如果是前者,您可以使用FormHelper::select() 中的options 键从一个数组中填充多个选择:

    控制器:

    $this->loadModel('Country');
    $this->set('countries', $this->Country->find('list'));
    

    查看:

    $this->Form->select('UserBillingInfo.country_id', $countries);
    $this->Form->select('UserShippingInfo.country_id', $countries);
    etc...
    

    否则,我通常通过在我的模型之间创建适当的关联来处理这种情况,然后使用Model::find('list') 或自定义模型方法来检索选项。如果您正确命名变量,options 变量将自动用作您选择的选项:

    控制器:

    $this->set('countries', $this->User->UserBasicInfo->Country->find('list'));
    

    查看:

    $this->Form->input('UserBasicInfo.country_id');
    

    【讨论】:

      【解决方案2】:

      Model::query() 在 cakephp 中做任何事情都不是最好的。

      在您正在使用的 UsersController 操作中

      $this->set('countries', $this->User->Country->find('list'));
      

      在编辑/添加表单中

      $this->Form->input('country_id');
      

      【讨论】:

        【解决方案3】:

        我对这种选择元素使用视图助手。如果我以你的情况为例,我会这样做:

        控制器:

        class UsersController extends AppController {
              ....
              public $helpers = array('Common');
              ....
        }
        

        帮手:

        class CommonHelper extends AppHelper {
              ....
              public function get_country_list() {
                    App::import( 'Model', 'Country' );
                    $objCountry = new Country();
                    $countries = $objCountry->find( 'list' );
                    return $countries;
              }
              ....
        }
        

        查看:

        ....
        echo $this->Form->input('country_id', array(
             'options' => $this->Common->get_country_list(),
             'value' => !empty($data['UserBasicInfo']['country_id']) ? $data['UserBasicInfo']['country_id'] : ''
        ));
        ....
        

        条件是您必须拥有 Country 模型。通过这种方式,您可以填充任何下拉菜单。干杯!!!

        【讨论】:

        • 这违反了 MVC 模式。
        • 对不起,你能告诉我它是如何违反 MVC 模式的吗?那么Helper的目的是什么?
        • 阅读这本书,它有一个关于 MVC 和 Helpers 的部分 -> book.cakephp.org。 App::import() 在这里也是错误的,直接实例化模型也是不行的。
        • 感谢 burzum 指出这一点。我总是喜欢遵循最佳实践。我将改变我上面提到的编码方式。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多