2014-03-29 61 views
1

我有兩個表,「用戶」和「崗位」,看起來像這樣:如何將用戶ID用作外鍵?

users: 
- id 
- username 
- password 
... 

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

基本上,用戶有多個帖子(博客型職位)。現在,我試圖以登錄用戶的身份創建一個新帖子,但是我無法使其工作。下面是我做了什麼:

// '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')); ?> 

如果我寫了一個帖子,點擊「發佈」,我得到一個完整性約束違規:

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) 

我失去了一些東西在這裏?它看起來像用戶ID不保存到模型。

編輯:

我忘了提,數據庫錯誤還打印出SQL查詢,這顯然是錯誤的:

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

有沒有任何的ID ...

+0

看看是否有幫助。 http://stackoverflow.com/a/16805528/1003917 –

+0

Post模型中的$ belongsTo變量不需要指定foreignKey - 如果不指定任何其他內容,CakePHP將自動查找名爲「user_id」的列 – jackel414

+0

你是否允許在帖子表中的user_id字段中爲空? – makallio85

回答

3

您需要做到這一點:

// 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它的工作。謝謝! – manabreak

0

我只是複製書在這裏,我沒有使用CakePHP的根本!

根據這本書:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html則 '的hasMany' 的關係應該類似於:

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

您有:

公共$的hasMany =陣列( '郵政');

是否應該提及您的類名? 即

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

有了這個那麼ORM可以解決如何類涉及什麼在運行時練習I.

相關問題