2016-12-27 65 views
1

我想在CakePHP中集的关联 my db 两型:在控制器协会CakePHP的3倍

namespace App\Model\Table; 
class UsersTable extends Table { 

    public function initialize(array $config) 
    { 

     $this->hasOne('Scores',[ 
      'className' => 'Scores', 
      'conditions' => '', 
      'dependent' => true 
     ]); 
    } 

} 

class ScoresTable extends Table { 
    //var $name = 'Scores'; 
    public final $connection = ConnectionManager::get('default'); 
    public function initialize(array $config) 
    { 
     $this->belongTo('Users', 
      'foreignKey' => 'user_code_Student', 
      'joinType' => 'INNER', 
     ); 
    } 
} 

性能指标:

public function index() { 
    //$connection = ConnectionManager::get('default'); 
    $modelUser = $this->loadModel('Users'); 
    $dataUser = $modelUser->find('all')->contain(['Score']); 
    /*$data = array(
     /*'listUser' => $modelUser->find('all', array(
      'conditions' => array('email LIKE' => '%gmail.com'), 
      'limit' => 2 
     )),$connection 
       ->execute('SELECT * FROM users WHERE email like :email limit 3', ['email' => '%gmail.com']) 
       ->fetchAll('assoc') 
     'listUser' => $this->paginate($modelUser->find('all')), 
     'title' => 'Demo MVC' 
    );*/ 
    $data = array(
     'listUser' => $dataUser 
    ); 
    $this->set('data', $data); 

} 

当我运行它,显示以下错误:Users is not associated with Score

你能帮助我吗?

回答

1

你的关系看起来像invalid.Try这样:

用户表

public function initialize(array $config) 
{ 

    $this->hasOne('Scores',[ 
     'foreignKey' => 'user_code_Student' 
    ]); 
} 

成绩表

public function initialize(array $config) 
{ 
    $this->belongsTo('Users', // you wrote here belongTo that should be belongsTo instead 
     'foreignKey' => 'user_code_Student', // is user_code_Student foreignKey ??? 
     'joinType' => 'INNER', 
    ); 
} 

,改变这一点:

$dataUser = $modelUser->find('all')->contain(['Scores']); // not Score 
+0

寻求帮助。但它仍然错误。 –

+0

Tks寻求帮助。但它仍然错误。 完全错误显示:表“Cake \ ORM \ Table”与“得分”没有关联 我是新的,我不确定约定:名称文件,名称类。 文件模型:User.php,Score.php 名称类模型和控制器如上。 你能帮助我吗? –

+0

查看更新后的答案.. –