2016-06-28 2 views
1

을 저장하기 전에 I는 다음과 같습니다 컨트롤러의 기능을 가지고있다. 내가 새 방을 추가하고 사용자가 양식을 통해 방 안에있는 사람을 선택하도록하면 그 방은 저장되고 beeing되지만 $ room-> users = [$ user_field]를 통해 첫 번째 사용자를 직접 추가하고 싶을 때 ; 그것 beeing 저장되지 않습니다. $ room 객체를 파일에 로깅하고 두 객체가 동일합니다 (양식을 통해 사용자를 추가 한 후 코드를 통해 사용자를 추가 한 후). 도와주세요 :(CakePHP의 3 개 데이터 연결

어쩌면 내가 모델의를 BeforeSave() 또는 afterSave()를 사용해야합니까?

내가 와 솔루션 도움을 Code.Working 발견 솔루션. 을 대신

$this->loadModel('Users'); 
을 추가하는

to 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']); 
} 

답변

0

당신이) 특정 일, 발견의 반환 값 (에 사용자의 집합을 줄이기 위해 쿼리 개체하지 않는 경우 : 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')); 
+0

안녕하세요, 답해 주셔서 감사합니다. 내가 어디 컨트롤러에 귀하의 솔루션을 넣어 필자는 다음과 같은 오류가 발생했습니다 : boolean에 대한 멤버 함수 user() 호출. 이걸 내가 어떻게해야합니까? – Barteo

+0

Auth Plugin을로드 했습니까? Auth를 변수에 저장하고 print_r()을 뷰에 저장하는 것이 도움이 될 수 있습니다. $ this-> set ('auth', $ this-> Auth); 보기에서 : print_r ($ auth); –

0

U 도움이 될 :

http://api.cakephp.org/3.2/class-Cake.ORM.Association.BelongsToMany.html#_link

을 링크가 링크 수 방 객체에 대한 사용자 객체를 쉽게 그리고 그것이 내가 생각하는 더 아름다운 해결책입니다. 가정하면 당신은 제대로 ofc의 협회를 설정했습니다!

행운을 빕니다 :)

+0

내가 이상한 "링크"사용자 나중에 관리,하지만 couldnt "링크"작동하도록합니다.아프기 때문에 더 많은 시간을 보내고 대답을 찾으십시오. 팁 고마워! – Barteo

0

내가 컨트롤러 내부의 모델을로드에서 다른 방법이 dirty() 방법을 사용 할 수 있다고 생각.

Log::debug($room); 바로 뒤에 $rooms->dirty('users', true);을 삽입하고 사용자의로드 모델에 댓글을 남깁니다. 이렇게하면 'rooms'의 '사용자'연결이 으로 더럽고으로 표시되므로 $this->Rooms->save($room)이 호출 될 때 저장됩니다.

시도해주세요.)