How to merge exists data with new data? - php

Method 1 : Here I wrote the code for insert booking seat data into the database
Problem : When I book new seat it will creating new row so I'm getting duplicate rows so I tried method 2
Method 1 code :
$booking = new Bookings();
$booking->users_id = 4;
$booking->schedules_id = $schedules_id;
$booking->buses_id = $buses_id;
$booking->routes_id = $routes_id;
$booking->seat = implode(',', $seat);
$booking->price = $request->price;
$booking->profile = 'pending';
Method 2 : Here checking schedules_id equal to exists schedules_id then update seat and other data's
Problem : Insert new data updating old data
Method 2 code :
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id], // match the row based on this array
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => json_encode($seat),
'price' => $request->price,
'profile' => 'pending',
]
);
// I don't know this is logically correct or wrong
My idea : Here I'm retrieving old data and storing into one variable then merging old data and new data into one column
Problem : Getting error.
My idea code :
$extSeat = DB::table('bookings')->select('seat')->get();
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id],
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => implode(",", array_merge($seat,$extSeat)),
'price' => $request->price,
'profile' => 'pending',
]);
what i actually need ? : i need merge exists data with new data without updating.
Old data look like A1,B1
when insert new data like C1
i need data like this A1,B1,C1
I hope I explain clear enough. Any help is appreciated, thank you.

I don't know this is a correct logic or not but works for me, any other suggestions are welcome.
$extSeat = DB::table('bookings')->select('seat')->first();
$extSeat = explode(",", $extSeat->seat);
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id],
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => implode(",", array_merge($seat,$extSeat )),
'price' => $request->price,
'profile' => 'pending',
]);

Related

Laravel UpdateOrCreate To Be Different values on Create on Update

Is there something like UpdateOrCreate I can use to have different values on create and on update. Meaning if it’s updating i don’t want it to change a certain column but i want it to insert the first time.
eg
$person = ['name'=> 'John', 'age' => 6, 'joined' => '2017-01-01'];
If John exists update age. If it doesn’t insert age and joined;
People::updateOrCreate(
['name' => $person['name']],
['age' => $person['age'], 'joined' => $person['joined']]
)
will update joined every time and i don't wanna change it.
You can use updateOrNew which doesn't persist it to the database and then check if it is not already in the database you can change the property you want to change.
$record = People::updateOrNew(
['name' => $person['name']],
['age' => $person['age']]
);
if(!$record->exists()) {
$record->joined = $person['joined'];
}
$record->save();
But if you are only trying to get the record if it exists and create it if it doesn't, use firstOrCreate() instead. That won't affect existing records, only return them, and it will create the record if it doesn't exist.
There is no any other option else you can try following:
$person = People::where('name', $name)->first();
if (!is_null($person)) {
$person->update([
'age' => $age
]);
}else{
$person = People::create([
'name' => $name,
'age' => $age,
'joined' => date('Y-m-d')
]);
}

Codeigniter, mysql, select_max and add 1 before inserting another record

When I insert a new record into a database table, I need to take an existing previous value of a column called el_order, add +1, and use that new el_order+1 to insert the new record with that value in the column.
I can't use autoincrement because I need to do some things with that column (reorder, move, etc) and have to use it as an integer.
Table
ID name el_order
1 1 1
21 bla 2
2 2 3
--NEW-- --NEW-- 3+1 (NEW)
I add a new record, and need to insert it with 3+1 in it's el_order column...
I have tried this, but no luck:
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio');
$eldi_key = url_title($this->input->post('id'), 'underscore', TRUE);
$el_order = $res+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);
$this->db->insert('elem_diccio', $datos);
Just like this
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio')->row()->el_order;
$eldi_key = url_title($this->input->post('id'), 'underscore', TRUE);
$el_order = $res+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);
$this->db->insert('elem_diccio', $datos);
$res is a CI_DB_mysqli_result Object. To get the column, you need
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio')->row();
$el_order = $res->el_order+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);

Save all record records using request->all in Laravel

Laravel provides a great help for developers to save all input fields of a form which is one record with one line of code.
like if I want to save a form which has multiple input fields and one record to database like:
then I can save it with below code and it works great:
SaveOrder:: create($request->all());
Now I have a question. If I have multiple records (multiple rows) in a form and I can add new rows with a button pressed. Then how can I save all records with above code?
Like:
It's easy to do that using Eloquent :
$data = array(
array('field1'=>'value1', 'field2'=> value2),
array('field1'=>'value1', 'field2'=> value1),
//...
);
Model::insert($data);
Assuming your input names look something like name[], since you can add rows on the fly, you can retrieve the input as an array, and insert them using something like this:
$data = [];
$names = request('name');
$product_names = request('product_name');
$product_colour = request('product_colour');
$product_size = request('product_size');
for ($i = 0; $i < count($names); $i++) {
// Add checks to make sure indices actually exist, probably using preprocessing in JS
$data[] = [
'name' => $names[$i],
'product_name' => $product_names[$i],
'product_colour' => $product_colour[$i],
'product_size' => $product_size[$i],
];
}
Model::insert($data);
The best answer for this question is using foreach statement. Like:
$CustomerName= $request -> input('CustomerName');
$ProductId= $request -> input('ProductId');
$ProductName= $request -> input('ProductName');
$ProductColor= $request -> input('ProductColor');
foreach( $ProductId as $key => $n ) {
SaveOrder::insert(
array(
'CustomerName' => $CustomerName[$key],
'ProductId' => $ProductId[$key],
'ProductName' => $ProductPrice[$key],
'ProductColor' => $ProductQuantity[$key],
)
);}
Use upsert
If you use Laravel 8 or above, you can make use of upsert. Such an useful function to insert or update matching records at the same time.
SaveOrder::upsert($request->all(), ['id'], ['CustomerName', 'ProductName', 'ProductColor', 'ProductID']);
The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database. The upsert method will automatically set the created_at and updated_at timestamps if timestamps are enabled on the model:
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);
Read the documentation on Laravel Upsert

How to update multiple data in CakePHP

I need to save multiple rows with the different condition for each row.
Like :
Update orderdetails SET data = "'.$json1.'" WHERE order_id = 1;
Update orderdetails SET data = "'.$json2.'" WHERE order_id = 2;
Update orderdetails SET data = "'.$json3.'" WHERE order_id = 3;
Update orderdetails SET data = "'.$json4.'" WHERE order_id = 4;
Update orderdetails SET data = "'.$json5.'" WHERE order_id = 5;
I know the single row updation method of CakePHP, that I can run 5 times form to update all row.
But I want to save this by just only one line code that can run above query.
My Code
$update = array(
array('data' => $json1,'order_id' => 1),
array('data' => $json2,'order_id' => 2),
array('data' => $json3,'order_id' => 3),
array('data' => $json4,'order_id' => 4),
array('data' => $json5,'order_id' => 5)
);
$this->Orderdetail->saveMany($update);
So, is there any way in CakePHP to achieve it...?
If I understand the above problem currently, you can achieve this by using the saveMany function in cakePHP. All you have to do is convert the data that you want to save in the form of an array and pass that single array to the saveMany function.
See here for more details
Here is a code sample for the above details in cakePHP 3:
$saveData = [
[
'order_id' => 1,
'data' => $json1
],
[
'order_id' => 2,
'data' => $json2
],
[
'order_id' => 3,
'data' => $json3
],
[
'order_id' => 4,
'data' => $json4
],
[
'order_id' => 5,
'data' => $json5
]
];
$orderDetails = TableRegistry::get('Orderdetails');
$entities = $orderDetails->newEntities($saveData);
$result = $orderDetails->saveMany($entities);
For cakePHP 2.x:
See here for more details
Hope this is what you are looking for.
Edit: Based on the updated requirements, I guess the only way to achieve it is to make a custom query by using the Model->query method. You'll have to form a custom query for that which updates all the records in one go.

How can i update or insert compare two fields from database

I want to compare either mobile or email fields exists in database it should update row else insert row
$ref = Ref::updateOrCreate(
[
'mobile' => $request['mobile'],
'email' => $request['email_address']
],
[
'firstname' => $request['firstname'],
"lastname" => $request['lastname'],
"mobile" => $request['mobile'],
"email" => $request['email_address'],
"mobile_verified" => $req->session()->get('mobile_verified'),
"quiz_data" => $req->session()->get('quiz_data'),
"verification_token" => $req_token
]
);
Do like this
$result= DB::statement("INSERT INTO table_name
(firstname,lastname,mobile,email,mobile_verified,quiz_data,verification_token)
VALUES ('".$request['firstname']."','".$request['lastname']."','".$request['mobile']."','"
.$request['email_address']."','".$req->session()->get('mobile_verified')."','"
.$req->session()->get('quiz_data')."','".$req_token."',)
ON DUPLICATE KEY UPDATE mobile = VALUES(mobile),email = VALUES(email);");
Replace table_name with your table name and try .
Here your mobile and email will be updated if the data is present before.
There is no Laravel function to compare on either field, you will have to execute two queries manually.
// Find an existing Ref
$ref = Ref::where('mobile', $request['mobile'])
->orWhere('email', $request['email_address'])
->first();
// Test if exists
if (isset($ref))
{
$ref->update([
// Update fields
]);
}
else
{
$ref = Ref::create([
// Create fields
]);
}

Categories