我的数据库中有用户,团队和teams_users表。当我创建一个新团队时,我想将团队和用户以及一些其他信息保存到连接表中。但是,CakePHP 3似乎没有认识到用户和团队之间的关系。
\模型\表\ UsersTable.php
$this->belongsToMany('Teams', [
'joinTable' => 'teams_users',
]);
\模型\表\ TeamsTable.php
$this->belongsToMany('Users', [
'joinTable' => 'teams_users',
]);
\模型\表\ TeamsUsersTable.php
$this->belongsTo('Teams');
$this->belongsTo('Users');
\控制器\ TeamsController.php
function Create() {
...
$user = $teamsTable->Users->get($this->Auth->user('id'));
$user->_joinData = $teamsTable->TeamsUsers->newEntity();
Error: Table "App\Model\Table\TeamsTable" is not associated with "TeamsUsers"
答案 0 :(得分:1)
首先,您应该使用through选项
然后有很多人认为你可以这样做:
然后_joinData不需要是TeamsTables
对象,可以是一个简单的实体(参见manual):
$user->_joinData = new Entity();
或者您可以加载模型
$this->loadModel('TeamsUsers')
$user->_joinData = $this->TeamsUsers->newEntity()
答案 1 :(得分:1)
最后是这样的:
感谢所有好的建议。到底是这样的:
if ($this-request->is('post')) {
$team = $this->Teams->patchEntity($team, $this->request->data);
$user = $this->Teams->Users->get($this->Auth->user('id'));
$teams->save($team);
$user->_joinData = new Entity();
$user->_joinData->nickname = $nickname;
$this->Teams->Users->link($team, [$user]);
$teams->save($team);
}