Best way to load models in CakePHP 2.0

后端 未结 3 1815
后悔当初
后悔当初 2020-12-13 10:18

I\'m not sure of the best way to load models in CakePHP 2.0 now.


Question 1

I have a model where more than one database field is relat

相关标签:
3条回答
  • 2020-12-13 10:32

    The preferred way is

    $this->load('MyModel');
    

    However, you can also use

    public $uses = array('DefaultModel', 'MyModel');
    .
    .
    $this->MyModel->field(...);
    

    Cake supports both and you are free to use anyone you like.

    0 讨论(0)
  • 2020-12-13 10:41

    For Question 1

    As per your structure there is an association between Customer and Country model i think so we don't need to load model. We can create virtual association for each id such as,

     'CountryOrigin' => array(
      'className' => 'Country',
      'foreignKey' => 'country_origin_id',
      'dependent' => true,
      'conditions' => '',
      'fields' => '',
      'order' => '',
      'limit' => '',
      'offset' => '',
      'exclusive' => '',
      'finderQuery' => '',
      'counterQuery' => ''
    )
    
    
    'CountryResidence' => array(
      'className' => 'Country',
      'foreignKey' => 'country_residence_id',
      'dependent' => true,
      'conditions' => '',
      'fields' => '',
      'order' => '',
      'limit' => '',
      'offset' => '',
      'exclusive' => '',
      'finderQuery' => '',
      'counterQuery' => ''
    )
    

    By doing this we can create an association between models so we don't want to load model explicitly

    Loading model is good when we don't have an association for that we can use as,

    Syntax for load Model is For single model load

    $this->loadModel('Country');
    

    This will be more useful if we want to load model for particular action or condition

    If we wan to use throughout the controller we can use $uses variable For multiple model load.

    public $uses = array('Country','OtherModel');
    

    we can access model like,

    $this->Country->find('count');
    
    0 讨论(0)
  • 2020-12-13 10:46

    This should be simple to understand. If you are using a controller and you need to load another model, you can call:

    $this->loadModel('SomeModel');
    

    Then you can make calls to the model like you normally would:

    $this->SomeModel->read(null, '1');
    

    App::uses is for lazy loading of classes. So you can still load a model using uses:

    App::uses('MyModel', 'Model');
    

    But then you will need to call it differently:

    $MyModel = new MyModel();
    $MyModel->read(null, '1');
    

    or

    MyModel::read(null, '1');
    

    It just depends on where and how you want to use it.

    0 讨论(0)
提交回复
热议问题