简体   繁体   English

Cakephp 3种形式,插入到FOREIGN KEY中

[英]Cakephp 3 forms, insert into FOREIGN KEY

Here is are my cods: 这是我的鳕鱼:

<?= $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();?>

And here is my Controller: 这是我的控制器:

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

The Problem is the Problem: 问题是问题:

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

But i need : 但是我需要 :

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

The Preoblem is that i need to insert it in Controller not in view. Preoblem是我需要将其插入Controller中而不在视图中。 Can someone help me? 有人能帮我吗?

Assuming that $user_id and $picture_id are variables that have been declared in your controller function, and have been properly checked for security if they are coming from user input (eg if they're in the URL, you've confirmed that they are okay and not just trusted them because the URLs that you give people links to are always valid), then the following should work: 假设$user_id$picture_id是在控制器函数中声明的变量,并且如果它们来自用户输入(例如,如果它们在URL中),则已经经过了正确的安全性检查(例如,如果它们在URL中,则表明它们可以)并且不仅仅信任他们,因为您提供给人们链接的URL始终是有效的),那么以下内容应该有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM