CakePHP 3 - 无法保存外键

时间:2017-02-16 13:50:44

标签: php model cakephp-3.0

所以,我有一个名为 posts 的表,另一个名为 users

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `users_id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `description` varchar(2000) NOT NULL,
  `views` int(11) NOT NULL DEFAULT '0',
  `status` int(1) NOT NULL,
  `created` datetime DEFAULT CURRENT_TIMESTAMP,
  `modified` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  `created` datetime DEFAULT CURRENT_TIMESTAMP,
  `modified` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这些是相应的模型帖子用户

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('posts');
        $this->displayField('title');
        //$this->primaryKey(['id', 'users_id']);
        $this->primaryKey(['id']);

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'users_id'
        ]);
    }

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('users');
        $this->displayField('name');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('Posts', [
            'foreignKey' => 'id'
        ]);
    }

问题在于,当我输入新帖子时,users_id的值变为0,即使在调试模式下它显示为1.这是调试:

{

    'users' => [
        'users_id' => '1'
    ],
    'title' => 'Teste title',
    'description' => 'Test desc',
    'status' => (int) 1,
    '[new]' => true,
    '[accessible]' => [
        '*' => true
    ],
    '[dirty]' => [
        'users' => true,
        'title' => true,
        'description' => true,
        'status' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Posts'

}
{ "users": { "users_id": "1" }, "title": "Teste title", "description": "Test desc", "status": 1 }

这些分别是控制器和视图:

public function add()
    {
        $post = $this->Posts->newEntity();
        if ($this->request->is('post')) {
            $post = $this->Posts->patchEntity($post, $this->request->data, ['associated' => ['Users']]);
            if ($this->Posts->save($post)) {
                $this->Flash->success(__('The post has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The post could not be saved. Please, try again.'));
        }
        $users = $this->Posts->Users->find('list', ['limit' => 200]);
        $this->set(compact('post', 'users'));
        $this->set('_serialize', ['post']);
    }

echo $this->Form->create($post);
echo $this->Form->input('users.users_id', array('default' => 1));
echo $this->Form->input('title');
echo $this->Form->input('description', ['rows' => '3']);
echo $this->Form->input('status', array('type'=>'select', 'options'=>array(1 => 'Enabled',2 => 'Disabled'), 'default'=>'1'));
echo $this->Form->button(__('Save Post'));
echo $this->Form->end();

我不知道可能导致错误的原因,代码看起来和我检查过的其他代码相同。

3 个答案:

答案 0 :(得分:0)

问题是表格,你应该使用:

$this->Form->input('users.id', array('default' => 1));

而不是

$this->Form->input('users.users_id', array('default' => 1));

另外,在保存数据时不要忘记关联Users表:

$posts = TableRegistry::get('Articles');
$post = $posts->newEntity($data, [
    'associated' => ['Users']
]);
$posts->save($post);

参考: https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongsto-associations

修改

我建议的方法适用于不同类型的实体,如类别,如果你必须与用户合作,更容易和更安全@Manohar Khadka的建议

答案 1 :(得分:0)

我认为你正在经历一些混乱。

虽然取代:

echo $this->Form->input('users.users_id', array('default' => 1));

人:

echo $this->Form->input('users_id', array('default' => 1));

只会解决您的问题,您需要了解以下事项。

<强> 1. When to use association on saving ?

  

如果您要在多个表格中保存记录,则只需要使用关联,否则您不需要这样做以保存记录。

如果您只需要在posts表上保存数据,只需执行以下操作:

$post = $this->Posts->patchEntity($post, $this->request->data]);

<强> 2. CakePHP Conventions

  

遵循CakePHP惯例会很容易。

如果您的表名是用户,则另一个表的外键将是user_id(而不是users_id)。当您更改此内容时,不要忘记更改相应模型中的关系。

并在表单中替换此行:

echo $this->Form->input('users.users_id', array('default' => 1));

人:

echo $this->Form->input('user_id', array('default' => 1)); 
// I consider user_id would be your field instead of users_id

答案 2 :(得分:0)

谢谢大家的建议,我同意@Manohar Khadka的说法,数据库有点乱,我会发现这个。但问题出在这里:

$post = $this->Posts->newEntity();
if ($this->request->is('post')) {
    $post = $this->Posts->patchEntity($post, $this->request->getData());
    $post->users_id = $post['users']['users_id'];
    if ($this->Posts->save($post)) {
        $this->Flash->success(__('The post has been saved.'));

        return $this->redirect(['action' => 'index']);
    }
    $this->Flash->error(__('The post could not be saved. Please, try again.'));
}
$users = $this->Posts->Users->find('list', ['limit' => 200]);
$this->set(compact('post', 'users'));
$this->set('_serialize', ['post']);

具体在这一行:

$post->users_id = $post['users']['users_id'];

未收到“users_id”值,因此它总是为0。