问题
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