your programing

CakePHP에서 다른 모델 내에서 하나의 모델을 사용할 수 있습니까?

lovepro 2020. 12. 26. 16:17
반응형

CakePHP에서 다른 모델 내에서 하나의 모델을 사용할 수 있습니까?


한 모델 내에서 다른 모델을 사용할 수 있습니까?

예 :

<?php
class Form extends AppModel
{
    var $name='Form';
    var $helpers=array('Html','Ajax','Javascript','Form');
    var $components = array( 'RequestHandler','Email');

    function saveFormName($data)
    {
        $this->data['Form']['formname']=$data['Form']['formname'];
        $this->saveField('name',$this->data['Form']['formname']);
    } 

    function saveFieldname($data)
    {
        $this->data['Attribute']['fieldname']=$data['Attribute']['fieldname'];
    }

}
?>

오래된 실이지만 나는 대답이 불완전하고 "왜"가 부족하다고 믿기 때문에 차임 할 것입니다. CakePHP에는 모델을로드하는 세 가지 방법이 있습니다. 컨트롤러 외부에서는 두 가지 방법 만 작동하지만 세 가지를 모두 언급하겠습니다. 버전 가용성에 대해서는 확실하지 않지만 이것은 핵심 요소이므로 작동 할 것이라고 믿습니다.

App::import()require()파일 만 찾아서 s를 수행하고이를 사용하려면 클래스를 인스턴스화해야합니다. import()클래스 유형, 이름 및 파일 경로 세부 사항을 알 수 있습니다 .

ClassRegistry::init()파일을로드하고 인스턴스를 객체 맵에 추가 한 다음 인스턴스를 반환합니다. 이것은 정상적인 수단을 통해 클래스를로드 할 때 발생하는 "Cake"작업을 설정하기 때문에 무언가를로드하는 더 좋은 방법입니다. 내가 유용하다고 생각한 클래스 이름에 대한 별칭을 설정할 수도 있습니다.

Controller::loadModel()ClassRegistry::init()컨트롤러의 속성으로 모델을 사용 하고 추가합니다. 또한 $persistModel향후 요청에 대한 모델 캐싱을 허용 합니다. 이것은 컨트롤러에서만 작동하며 귀하의 상황이라면 다른 방법보다 먼저이 방법을 사용합니다.


이 두 가지 방법 중 하나를 사용하여 모든 모델 / 컨트롤러 내에서 다른 모델의 인스턴스를 만들 수 있습니다.

Cake 1.2를 사용하는 경우 :

App::import('model','Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);

Cake 1.1을 사용하는 경우 :

loadModel('Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);

모두가 놓친 명백한 해결책은 적절한 경우 두 모델 간의 연관성 을 만드는 것 입니다. 이를 사용하여 한 모델을 다른 모델 내부에서 참조 할 수 있습니다.

class Creation extends AppModel {
    public $belongsTo = array(
        'Inventor' => array(
            'className'  => 'Inventor',
            'foreignKey'  => 'inventor_id',
        )
    );

    public function whoIsMyMaker() {
        $this->Inventor->id = $this->field('inventor_id');
        return $this->Inventor->field('name');
    }
}

CakePHP 1.2에서는 다음을 사용하는 것이 좋습니다.

ClassRegistry::init('Attribute')->save($data);

이것은 단순히 할 것입니다

<?php
   class Form extends AppModel
    {
       //...
          $another_model = ClassRegistry::init('AnotherModel');
       //...  
    }
?>

CakePHP 3에서는 TableRegistry :: get (modelName)을 사용할 수 있습니다.

use Cake\ORM\TableRegistry;

$itemsOb = TableRegistry::get('Items');
$items = $itemsOb->find("all");
debug($items);

Model_A 내에서 Model_B를 사용하려면 Model_A 파일의 시작 부분에 다음 줄을 추가합니다.

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

그러면 Model_A에서 사용할 수 있습니다. 예를 들면 :

$Model_B = new Model_B_ClassName();
$result = $Model_B->findById($some_id);

var $uses = array('ModeloneName','ModeltwoName');

사용하여 $uses속성을, 당신은 컨트롤러 대신 사용하여 여러 모델을 사용할 수 있습니다 loadModel('Model Name').

App::import('model','Attribute');

한 모델을 다른 모델에 사용하는 방법입니다. 가장 좋은 방법은 사용하는 것입니다.

참조 URL : https://stackoverflow.com/questions/980556/can-i-use-one-model-inside-of-a-different-model-in-cakephp

반응형