cakephp3窗体,插入外键

ztyzrc3y  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(348)

这是我的密码:

<?= $this->Form->create('Posts', array('url' => array('controller' => 'MyController', 'action' => 'index')));?>
                        <?= $this->Form->input('title', array('type'=>'title','class'=>'form-control mr-sm-2'));?>
                        <?= $this->Form->textarea('text', array('type'=>'text','rows' => '3','class'=>'form-control'));?>
                        <?= $this->Form->submit('Posten', array('class'=>'btn btn-outline-success my-2 my-sm-0','style'=>'float:right'));?>
                    <?= $this->Form->end();?>

这是我的控制器:

$post = $this->Posts->newEntity();
    if ($this->request->is('post')) {
        $post = $this->Posts->patchEntity($post, $this->request->getData());
        debug($post);
        if ($this->Posts->save($post)) {

        $this->Flash->success(__('You have posted something.'));
        }

        return $this->redirect(['action' => 'index']);
    }else {
        $this->Flash->error(__('Error, plase check your'));
    }

问题在于:

INSERT INTO posts (title, text) VALUES (:c0, :c1);

但我需要:

INSERT INTO posts (title, text,user_id,picture_id) VALUES (a,b,$user_id,$picture_id);

问题是我需要将它插入控制器而不是视图中。有人能帮我吗?

hof1towb

hof1towb1#

假设 $user_id 以及 $picture_id 是在您的控制器函数中声明的变量,如果这些变量来自用户输入(例如,如果它们在url中,您已经确认它们是正常的,而不仅仅是信任它们,因为您提供给人们链接的url总是有效的),那么以下内容应该可以工作:

$post = $this->Posts->patchEntity($post,
    array_merge($this->request->getData(), compact('user_id', 'picture_id'))
);

相关问题