2016-12-27 66 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

查看更新後的答案.. –