inserting only in two columns of database using cakephp

寵の児 提交于 2020-02-06 07:28:50

问题


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

and in the controller 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?.

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


回答1:


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

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

So instead of doing

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

you can simply do

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

as explained here

Even simplier you can do

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

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

in the controller:

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


来源:https://stackoverflow.com/questions/49044697/inserting-only-in-two-columns-of-database-using-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!