我在cakephp中尝试设置关联 my db 两种模式:
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
你能帮助我吗?
答案 0 :(得分:1)
您的关系看起来无效。请尝试:
用户表
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