使用模型在 CakePHP 中创建 2 个表之间的关系以编写更少的代码

Creating relationship between 2 tables in CakePHP using models to write less code

我试着只说 CkMmUsersKta.user_id=CkSetupUser.id 并定义 CakePhp 中 2 个表之间的关系。 我在控制器中定义了模型并在函数中调用了模型,但显示

的未定义索引
$c['CkSetupUser']['user_name']

CakePHP 的 注意事项(8):未定义索引:CkSetupUser [APP\Controller\RealsController.php, line 67]

我的控制器:

class RealsController extends AppController {

   public $helpers = array('Html', 'Form');
   public $uses =array('CkMmUsersKta','CkSetupUser');

  public function index(){
   $this>loadModel('CkMmUsersKta');$this>loadModel('CkSetupUser');

   ini_set('memory_limit', '2000M');

   $cs=$this->CkMmUsersKta->find("all",array('fields'=>array('CkMmUsersKta.id')));

      foreach($cs as $c):
        echo $c['CkMmUsersKta']['id'].$c['CkSetupUser']['user_name']."<br />";
      endforeach;
   set_time_limit(0); 
   }
}

我的 CkSetupUser 模型:

    public $hasMany = array(
        'CkMmUsersKta' => array(
            'className'     => 'CkMmUsersKta',
            'foreignKey'    => 'user_id',
            'dependent'     => true
        )

    );

我的 CkMmUsersKta 模型:

    public $belongsTo = array(
        'CkSetupUser' => array(
            'className'    => 'CkSetupUser',
            'foreignKey'    => 'user_id'
        )

    );

问题是您只获取了 id 字段:

$cs=$this->CkMmUsersKta->find("all",array('fields'=>array('CkMmUsersKta.id')));

您还应该指定名称字段。

$cs=$this->CkMmUsersKta->find("all",array('fields'=>array('CkMmUsersKta.id','CkSetupUser.user_name' )));