2014-06-13 4 views
0

CakePHP에서 3 개의 테이블 사이의 올바른 관계를 생성하는 데 도움이 필요합니다. 이들은 :CakePHP의 테이블 간의 관계

  1. 사용자 - PK = user_id를
  2. 책 - PK = book_id
  3. books_users

나는이 책이 소속 된 사이에 내 users_books 테이블의 모든 관계를 포함하기 위해 노력하고 어떤 사용자, 그리고 그 반대의 경우 :

ID | user_id | book_id 
-------------------------- 
1  321   231 
2  24   58 
3  80   58 
4  24   75 
5  80   231 

내 접근 방식은 hasAndBelongsToMany-relation, bu 새 책을 추가 할 때 users_books-table에는 정보가 채워지지 않습니다.

내 컨트롤러에서 saveAll() 및 saveAssociated() - 메서드를 시도했지만 아무 것도 작동하지 않습니다.

아무도 내가이 모델을 작성하기 위해 모델에 넣어야 할 연관성 코드를 알려줄 수 있습니까?

public function addBook() { 
    $this->Book->create(); 

    $this->request->data['Book']['book_user_id'] = $this->Auth->user('user_id'); 
    $data = $this->request->data['Book']; 

    if (!$data['book_img']['name']) { 
     unset($data['book_img']); 
    } 

    if ($this->Book->saveAll($data)) { 
     $this->Session->setFlash(__('The book has been saved.')); 
     return $this->redirect(array('action' => 'index')); 
    } else { 
     $this->Session->setFlash(__('The book could not be saved. Please, try again.')); 
    } 
} 

다음은 새로운 배열 :

$test = array('User' => $this->Auth->user('user_id'), 'Book' => $data); 
pr($test); 

출력이 :

Array 
(
[User] => 4 
[Book] => Array 
    (
     [book_study_id] => ha_fil 
     [book_title] => The title 
     [book_price] => 123 
     [book_isbn] => 123 
     [book_user_id] => 4 
    ) 

) 사전에

감사합니다, 예스퍼. 당신이 의심 스러울 때 HABTM 꽤 혼란

+0

또한'view'와'controller' 코드를 넣으십시오. –

+0

@Anilkumar 컨트롤러 동작이 어떻게 보이는지 추가했는데, 내보기가 어떻게 보이는지 관련이 있습니까? –

+0

[Docs] (http://book.cakephp.org/2.0/ko/models/associations-linking-models-together.html#hasandbelongstomany-habtm) ... ** 표 이름은 규칙에 따라 사전 순으로 * . 연관 정의에서 사용자 정의 테이블 이름을 정의 할 수 있습니다. ** – Nunser

답변

1

...

the docs를 참조하십시오. 거기에서

당신이 저장된 배열 그래서

Array 
(
    [Recipe] => Array 
     (
      [id] => 42 
     ) 
    [Tag] => Array 
     (
      [name] => Italian 
     ) 
) 

, 당신이 원하는 무엇을 그 변환해야하는 방법의 예를 가지고, 당신은 ...이 배열을 저장해야

Array 
(
    [User] => Array 
     (
      [id] => $this->Auth->user('user_id') 
     ) 
    [Book] => Array 
     (
      [name] => book, 
      /* your other book stuff */ 
     ) 
) 
관계를 저장하려면

과 간단한 $this->save($suggestedBySOArray)을 수행하십시오.

더 많은 예제가 필요하면 docs에 대한 링크에서 HABTM에 데이터를 저장하는 방법에 대한 예제가 더 있습니다.

편집 : 나는 당신이 옳은 길을 얻을 수 있도록 좀 더 많은 코드를 추가 할 것입니다

. 자, 나는이 예제에서 것을 * 추측하고 있습니다. 질문이 없으므로
입니다. 새 책을 만들면 기존 사용자와 기존 책 간의 관계가 업데이트되지 않습니다.
2) 당신은 단지 그것을한다고

$this->Book->create(); 

//what did you intent to do with this piece of code btw? you don't have a "book_user_id" column anywhere 
//$this->request->data['Book']['book_user_id'] = $this->Auth->user('user_id'); 

$data = $this->request->data; 

if (!$data['Book']['book_img']['name']) { 
    unset($data['Book']['book_img']); 
} 

$data['User']['id'] = $this->Auth->user('user_id'); 

if ($this->Book->save($data)) { 
    $this->Session->setFlash(__('The book has been saved.')); 
    return $this->redirect(array('action' => 'index')); 
} else { 
    $this->Session->setFlash(__('The book could not be saved. Please, try again.')); 
} 

많지 않은 한 권의 책을 추가한다.

이제 더 이상 문서를 읽으십시오. 예와 모든 것이 있습니다.

또한 @Anilkumar가 HABTM 대신 hasMany를 사용하여 올바른 ("한 명의 사용자 만 책을 추가하려고합니다") 무엇을 의심하는지 생각한 경우.

+0

이 배열을 만드는 것을 도와 줄 수 있습니까? 나는 이것에 대해 생각할 수 없다 : ( –

+0

$ test = array ('User'=> $ this-> Auth-> user ('user_id'), 'Book'=> $ data); –

+0

No –