如何在cakephp中将数据插入数据库

时间:2013-11-28 00:46:45

标签: database cakephp insert

您好我有一个字段(url),我想将表单中输入的URL插入到数据库中

我的控制器中添加的功能如下所示:

public function add(){
    if($this->request->is('post')){

        // debug($this->Link->find('all'));//this works

        $link = $this->Link->findByUrl($this->request->data['link']['url']);
        if(empty($link)){
            //I will create the link
            $this->Link->create($this->request->data, true);//true = ignoring the ID
            $this->Link->save(null, true, array('url'));

            //null = because I ready wrote "$this->request->data" in create
            //true = I want to use VALIDATION
            //array = I choose to SAVE this field only
            echo "I've created the link";
            die($this->Link->id);
        }else {
            debug($link);
            die("The link is already in the database");
            //je dois récupérer le lien
        }

    }

如何在数据库中插入输入的链接?

1 个答案:

答案 0 :(得分:1)

不确定您使用的是哪个版本的Cake,但通常的工作方式是:

  • create()新参考
  • set()新数据
  • save()参考

示例:

        $this->Link->create();
        $this->Link->set($this->request->data['link']);
        $save = $this->Link->save();
        echo $save ? "I've created the link" : "Error creating link!";
        die($this->Link->id);