使用cakephp仅在数据库的两列中插入 [英] inserting only in two columns of database using cakephp

查看:36
本文介绍了使用cakephp仅在数据库的两列中插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我大约有30 40列,但只能插入2列进行练习.

I have about 30 40 columns but only inserting in 2 columns to practice.

现在这就是我要插入数据库的方式.

Right now this is how i am inserting into database.

UsersTable.php

public function createUser($data)
    {

        $usersTable = TableRegistry::get('users');
        $user = $usersTable->newEntity();

        $user->first_name = $data['first_name'];
        $user->first_name = $data['first_name'];


        $usersTable->save($user);
    }

并在控制器 UsersController.php

function signUp()
    {
        if($this->request->is('post')){
            $data['first_name']='test first name';
            $data['last_name']='test last name';
            $this->Users->createUser($data);
        }


        else{
            $this->viewBuilder()->Setlayout('signup');
        }
    }

这一切都很好,但是我怀疑这是实现这一目标的好方法吗?.

This is going fine but i have a doubt that is this a good way to do this?.

如果我必须插入15列,那么我必须像这样在模型中提及每个 entity 怎么办?

What if i have to insert 15 columns so i have to mention every entity in the model like this ?

$ user-> first_name = $ data ['first_name'];$ user-> first_name = $ data ['first_name'];

推荐答案

有一种方法可以将数据修补到实体中,因此您不必自己做: patchEntity()

There is a method used to patch the data into the entity so you don't have to do it by yourself: patchEntity()

patchEntity 检查传递的数组,并将值分配给实体的相应键.

patchEntity check for the passed array and assign the values to the correpsonding keys of the entity.

所以不要这样做

$user = $usersTable->newEntity();
$user->first_name = $data['first_name'];
$user->first_name = $data['first_name'];
$usersTable->save($user);

您可以简单地

$user = $usersTable->newEntity();
$usersTable->patchEntity($user, $data);
$usersTable->save($user);

这里

甚至可以简化

 $user = $usersTable->newEntity($data);
 $usersTable->save($user);

通常 $ data 来自请求查询子,您甚至不必自己创建数组

usually $data comes from the request query son you don't even have to create the array yourself

在控制器中:

$user = $usersTable->newEntity($this->request->data());

这篇关于使用cakephp仅在数据库的两列中插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆