2014-03-29 95 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.

相关问题