douxue7196 2017-02-16 13:50
浏览 44

CakePHP 3 - 无法保存外键

So, I have a table called posts and another called 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;

These are the respective models Posts and Users.

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'
        ]);
    }

The problem is that when I enter a new post, the value of users_id comes as 0, even though in debug mode it appears as 1. This is the debug:

{

    '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 }

These are respectively the controller and the view:

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();

I do not know what may be causing the error, the code seems the same as others I checked and that work.

  • 写回答

3条回答 默认 最新

  • dqvtm82066 2017-02-16 15:08
    关注

    the problem is the form, you should use:

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

    instead of

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

    Also don't forget to associate the Users table whenyou are saving the data:

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

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

    Edit

    The method I suggested works great with a different type of entity like Categories, if you have to work with Users is easier and safer the suggestion of @Manohar Khadka

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向