2014-03-29 3 views
1

내가 두 테이블을 가지고 '사용자'이처럼 보이는 '게시물':사용자 ID를 외래 키로 사용하는 방법은 무엇입니까?

users: 
- id 
- username 
- password 
... 

posts: 
- id 
- user_id (foreign key referencing users.id) 
- text 

기본적으로, 사용자가 여러 게시물 (블로그 형 게시물)가 있습니다. 이제 로그인 한 사용자로 새 게시물을 만들려고하는데 작동하지 않습니다. 여기에 내가 무슨 짓을했는지의 :

Error: SQLSTATE[23000]: Integrity constraint violation: 
1452 Cannot add or update a child row: a foreign key 
constraint fails (`yams`.`posts`, CONSTRAINT `user_id` 
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) 
ON DELETE NO ACTION ON UPDATE NO ACTION) 

내가 여기서 뭔가를 놓치고 있습니까 :

// 'User' model 
class User extends AppModel 
{ 
    public $name = 'User'; 
    public $hasMany = array('Post'); 

    ... 

// 'Post' model 
class Post extends AppModel 
{ 
    public $name = 'Post'; 
    public $belongsTo = array(
     'User' => array(
      'className' => 'User', 
      'foreignKey' => 'user_id' 
     ) 
    ); 

// In PostsController 
public function create() 
{ 
    if($this->request->is('post')) 
    { 
     $this->Post->create(); 
     if($this->Post->save($this->request->data) 
     { 
      // Success 
     } 
    } 
} 

// In the post view 
<?php echo $this->Session->flash('auth'); ?> 
<?php echo $this->Form->create('Post', array('action' => 'create')); ?> 
<fieldset> 
    <legend> 
     <?php echo __("Write a post"); ?> 
    </legend> 
</fieldset> 
<?php echo $this->Form->end(__('Post')); ?> 

내가 게시물을 작성하고 '포스트'를 클릭하면, 내가 무결성 제약 조건 위반을 얻을? 사용자 ID가 모델에 저장되지 않은 것 같습니다.

편집 : 전혀 ID가 없습니다

INSERT INTO `yams`.`posts` (`text`) VALUES ('this is a test post.') 

...

+0

도움이되는지 확인하십시오. http://stackoverflow.com/a/16805528/1003917 –

+0

Post 모델의 $ belongsTo 변수가 foreignKey를 지정할 필요가 없습니다. - CakePHP는 다른 것을 지정하지 않으면 "user_id"라는 열을 자동으로 찾습니다. – jackel414

+0

게시물 테이블의 user_id 필드에 null을 허용 했습니까? – makallio85

답변

3

당신이 필요합니다 :

내가 언급하는 것을 잊었다

, 데이터베이스 오류가 분명히 잘못 SQL 쿼리를 출력 이것을하십시오 :

// In PostsController 
public function create() 
{ 
    if($this->request->is('post')) 
    { 
     $this->request->data['Post']['user_id'] = $this->Auth->user('id'); 
     $this->Post->create(); 
     if($this->Post->save($this->request->data) 
     { 
     // Success 
     } 
    } 
} 
+0

Aaaand it was worked. 고맙습니다! – manabreak

0

나는 다만 여기 책을 베낄 것이다, 나는 cakePHP를 사용하지 않았다 조금도! 당신은이

class User extends AppModel { 
    public $hasMany = array(
     'Recipe' => array(
      'className' => 'Recipe', 
      'conditions' => array('Recipe.approved' => '1'), 
      'order' => 'Recipe.created DESC' 
     ) 
    ); 
} 

:

책에 따르면 :에 http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html 다음 'hasMany의'관계는 유사합니다

공공 $의 hasMany의 = 배열 ​​('포스트');

본인의 학급에 언급이 있어야합니까? 이와 즉

public $hasMany = array(
     'Post' => array(
      'className' => 'Post' 
      ) 
     ); 

다음 ORM 런타임에 기입하는 방법을 클래스가 이야기하고 무엇을 작업 할 수 있습니다.

관련 문제