CakePHP 3 - 保存前的数据关联

时间:2016-06-28 17:20:37

标签: php cakephp save

我在控制器中有功能,如下所示:

//Create room
public function createRoom(){
    $room = $this->Rooms->newEntity();
    if($this->request->is('post')){
        $room = $this->Rooms->patchEntity($room, $this->request->data);
        $user_field = $this->Rooms->Users->find()->where(['id' => $this->Auth->user('id')]);
        $room->users = [$user_field];
        $room->current = 1;
        $room->owner_id = $this->Auth->user('id');
        Log::debug($room);
        if($this->Rooms->save($room)){
            $this->Flash->success('You have created a new room.');
            return $this->redirect(['action' => 'index']);
        }
        else{
            $this->Flash->error('Error creating new room.');
        }
    }
    $games = $this->Rooms->Games->find('list', ['limit' => 200, 'keyField' => 'id', 'valueField' => 'name']);
    $this->set(compact('room', 'games', 'users'));
    $this->set('_serialize', ['room']);
}

表"用户"和"房间"在关联表中连接。当我运行添加一个新的房间,我让用户通过表单选择房间里的人然后保存,但当我想通过$ room-> users = [$ user_field]自己添加第一个用户时]。它没有被保存。我将$ room对象记录到文件中,两个对象都是相同的(在通过表单添加用户之后以及通过代码添加用户之后)。帮帮我:(

也许我应该在模型中使用beforeSave()或afterSave()?

我找到了一个带有 Code.Working 帮助的解决方案。 而不是添加

$this->loadModel('Users');

到initializie()方法我只是把它放在我的createRoom()函数中。

最终工作代码如下所示:

//Create room
public function createRoom(){
    $this->loadModel('Users');
    $room = $this->Rooms->newEntity();
    if($this->request->is('post')){
        $room = $this->Rooms->patchEntity($room, $this->request->data);
        $user_field = $this->Users->get($this->Auth->user('id'));
        $room->users = [$user_field];
        $room->current = 1;
        $room->owner_id = $this->Auth->user('id');
        Log::debug($room);
        if($this->Rooms->save($room)){
            $this->Flash->success('You have created a new room.');
            return $this->redirect(['action' => 'index']);
        }
        else{
            $this->Flash->error('Error creating new room.');
        }
    }
    $games = $this->Rooms->Games->find('list', ['limit' => 200, 'keyField' => 'id', 'valueField' => 'name']);
    $this->set(compact('room', 'games', 'users'));
    $this->set('_serialize', ['room']);
}

3 个答案:

答案 0 :(得分:0)

如果您没有将用户集减少到特定的用户,则find()的返回值始终是查询对象:Retrieving Data & Results Sets

尝试使用此方法将检索到的用户集减少到第一个:

$user_field = $this->Rooms->Users->find()->where(['id' => $this->Auth->user('id')])->first();

或者更好,如果' id'列是您的主键:

// In the initialize() method
$this->loadModel('Users');

// And in the action:
$user_field = $this->Users->get($this->Auth->user('id'));

答案 1 :(得分:0)

我想这会对你有所帮助:

FXML StackPane doesn't align children correctly

通过链接,您可以轻松地将用户对象链接到房间对象,这是我认为更美观的解决方案。假设你已正确设置了关联!

祝你好运:)

答案 2 :(得分:0)

我认为在控制器中加载模型的另一种方法可能是使用dirty()方法。

在您的情况下,您将在$rooms->dirty('users', true);之后立即插入Log::debug($room);并评论用户的加载模型。这会将“房间”的“用户”关联信号标记为,因此会在调用$this->Rooms->save($room)时将其保存。

试一试;)