Laravel DB update exception - php

Im trying to get exception if update method failed i just check this try catch block it dont return any exception because this project id do not exist in my database i have only about hundred records.
try {
$project = DB::table('project')
->where('prj_id', '987654' )
->update([
'prj_status' => 'open',
'prj_updated_date' => Carbon::now()
]);
}catch(\Exception $e){
dd($e);
}

An update on none-existing row do not fail in SQL. If you run a query like UPDATE foo SET bar = 'foobar' WHERE 1 = 2; your database would be happy to do the job and report back 0 rows updated.
You will have to check the value of $project to see if the update did update any rows

If you're using Laravel 5, use the model to dictate what will be stored in the DB eventually.
So, using your project model, you'll have something like:
$project = Project::findOrFail('987654')
->update([
'prj_status' => 'open',
'prj_updated_date' => Carbon::now()
]);
You'll get a not found exception if the id of what you're looking for doesn't exist.

$projects_updated = DB::table('project')
->where('prj_id', '987654' )
->update([
'prj_status' => 'open',
'prj_updated_date' => Carbon::now()
]);
if($projects_updated) {
// n rows updated, do something
}
else {
// nothing updated
}

Related

Eloquent update all column fields

I want to update all the tables in the Article migration to a specific Boolean value which is set by the user.
I have written this code:
public function changeComVote() {
$data = request()->validate([
'status' => 'required'
]);
Article::query()->update(['isOnly' => $data['status']]);
event(new changesMade);
}
Although $data['status'] doesn't get passed inside the query and nothing happens, when i set it manually it works like a charm, what could be the problem?
Using $data['status'] from request will give you a string as a result, not a boolean.
Try this way
Article::query()->update(['isOnly' => $data['status'] == 'true']);
You can delete that "query()" thing and use this instead
Article::update(['isOnly' => $data['status']]);
or
Article::update(['isOnly' => ($data['status']] === "true"));
You can also specify where the row by using id
Article::find($id)->update(['isOnly' => ($data['status']] === "true"));

Update record if column is not null else create new record in laravel

I have a users table and a tasks table. I have already many users record and now I need to add tasks for new users as well as for existing users. So for these I am using this query:-
$match = ['service_type_id' => 'IS NOT NULL'];
$model->tasksList()->updateOrCreate($match, [
'service_type_id' => $request->service_description_id,
'created_by' => $request->created_by,
]);
Here $model represents user model and I wanted to update only when the column is not null else create new record but everytime new record is created. Where am I getting wrong? Please help.
I'm not sure you can do this with a single Eloquent one-liner. What you're doing there would get interpreted at a string literal, service_type_id = "IS NOT NULL". You'll probably have to do something like this:
$action = $model->taskList()->whereNotNull('service_type_id')->doesntExist() ? 'create' : 'update';
$model->taskList()->$action([
'service_type_id' => $request->service_description_id,
'created_by' => $request->created_by
]);

Mysql record missing when server lag

Customer use the app which create the order to deliver goods. In the database, it will generate the order_delivery table;
And then generate the goods_stock_vary_history table that record the changes of goods stock;
They are in one transaction.
The order_delivery has one goods_stock_vary_history.
But one day the customer created the order when server lag. And then he exist the app and create order again.
After a while, he say he cannot see his order.
I found the record of goods_stock_vary_history and its field order_delivery_id has value 2;
So I try to find order_delivery that primary key is 2.
And I cannot find it. There have primary keys 1 and 3 etc. The primary key is auto increment;
order_delivery has soft delete only; Nobody can delete that record.
The project use Laravel5.1 and the codes like below:
DB::beginTransaction();
foreach ($order_goods_matrix as $order_id => $goods_matrix) {
$goods_amount = OrderServices::countGoodsColorSizeMatrixAmount($goods_matrix);
if($goods_amount==0){
DB::rollback();
Redis::del($user_id . '_good_delever');
return $this->fail(self::ERROR_CODE, "Deliver Fail. The count cannot be zero");
}
if (intval($order_id) > 0 && $goods_amount > 0) {
$goods_matrix = json_encode($goods_matrix, true);
// Create order delivery
$ret = OrderServices::createDelivery($exist_flag, $user_id, $store_id, $order_id, $goods_matrix, OrderDelivery::DELIVERY_TYPE_COMMON, $created_at);
if ($ret['code'] < 0) {
DB::rollback();
Redis::del($user_id . '_good_delever');
return $this->fail(self::ERROR_CODE, "Deliver Fail" . $ret['msg']);
}
$get_history_id_arr[] = $ret['get_stock_histtory']['goods_stock_vary_history_id'];
}
}
$store_goods_sku = GoodsServiceV3::getGoodsSku($store_id);
foreach ($get_history_id_arr as $get_history_id_info) {
$get_history_detail[] = GoodsStockServiceV2::getGoodsStockVaryHistoryDetail($store_id, $get_history_id_info);
}
DB::commit();
in the function createDelivery:
$order_delivery = array();
$order_delivery['order_id'] = $order_id;
$order_delivery['customer_id'] = $order_base["buyer_user_id"];
$order_delivery['delivery_goods_color_size_matrix'] = $delivery_goods_color_size_matrix;
$order_delivery['delivery_goods_amount'] = $delivery_goods_amount;
$order_delivery['operate_user_id'] = $user_id;
$order_delivery['delivery_type'] = $delivery_type;
$order_delivery['exist_flag'] = $exist_flag;
$order_delivery['deliver_timestamp'] = $created_at;
$order_delivery_id = OrderDelivery::insertGetId($order_delivery);
if ($order_delivery_id == false) {
return array('code' => -3, 'msg' => 'Deliver fail');
}
$reverse_delivery_goods_color_size_matrix_array = GoodsStockServices::reverseGoodsColorSizeMatrix($delivery_goods_color_size_matrix_array);
// create goods_stock_vary_history
$get_stock_histtory = GoodsStockServices::addStockVariation($exist_flag, $user_id, $store_id, $reverse_delivery_goods_color_size_matrix_array, GoodsStockServices::STOCK_TYPE_DELIVER, GoodsStockServices::STOCK_TYPE_DELIVER_DEFAULT_REMARK, $order_delivery_id, null, $order_base["buyer_user_id"], $created_at);
return array('code' => 0, 'order_delivery_id' => $order_delivery_id, 'get_stock_histtory' => $get_stock_histtory);
I found the reason.
I created a trigger to track each order_delivery records after be deleted.
And then I found that order_delivery record is still missing, and the track table doesn't have any records.
So the missing order_delivery record is not deleted by someone or some method.
So I think the missing record is not missing, it just rollback, and another order_delivery inserted before it rollback, that make it like missing.
And then I try to log every database operation result for getting details.
I found there is a line not deal with the fail operation.
These code is written two years ago, the transaction part is smelly, you need to manually rollback the fail operation. and return fail message.
The better way is like this:
DB::beginTransaction();
try {
...
OrderServices::createDelivery($exist_flag, $user_id, $store_id, $order_id, $goods_matrix, OrderDelivery::DELIVERY_TYPE_COMMON, $created_at);
...
DB::commit();
} catch(\Throwable $e) {
DB::rollback();
throw $e;
}
After I change it, the missing record phenomenon not showing again.

Not getting the id in where clause - Laravel 5.2

I need to get the record with special id and i have this in my method :
public function addedMark()
{
$user = Auth::user();
$subject = ClassSubject::where('teacher_id', $user->id)->pluck('id','subject_id');
return view('educator.account.marks', [
'user' => $user,
'marks' => StudentMark::where('subject_id', $subject)->get()
]);
}
When i do dd(ClassSubject::where('teacher_id', $user->id)->pluck('id','subject_id')); i see that I'm getting the information that i need, but when i do dd(StudentMark::where('subject_id', $subject)->get()); it returns an empty array.
Any idea why?
Change it to (whereIn)
'marks' => StudentMark::whereIn('subject_id', $subject)->get()
and let see what hapens
In $subjectyou have id and subject_id. You might wanna just take subject_id.
So change this: StudentMark::where('subject_id', $subject)->get()
to
StudentMark::where('subject_id', $subject[1])->get()

Update only one field on Cakephp 3

In some part of my app I need to update only the field is_active of some table with a lot of fields. What is the best approach to update only this field and avoid the validations and requiriments of all other fields?
And if you want to update particular row only , use this:
$users= TableRegistry::get('Users');
$user = $users->get($id); // Return article with id = $id (primary_key of row which need to get updated)
$user->is_active = true;
// $user->email= abc#gmail.com; // other fields if necessary
if($users->save($user)){
// saved
} else {
// something went wrong
}
See here (Updating data in CakePHP3).
This will work:
$users = TableRegistry::get('Users');
$query = $users->query();
$query->update()
->set(['is_active' => true])
->where(['id' => $id])
->execute();
http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data
When you don't want callbacks to be triggered, just use updateAll()
$table->updateAll(['field' => $newValue], ['id' => $entityId]);
Using the example here: http://book.cakephp.org/3.0/en/orm/database-basics.html#running-update-statements. Run the code below to update all records in table_name_here table with a new value for is_active column.
use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');
$connection->update('table_name_here', ['is_active' => 'new_value_here']);
I faced this issue when upgrading my project from 2.10 to 3.x.
In 2.10 you could update a single field using:
$this->Menus->saveField('css', $menucss);
But since this method was deprecated, we do as below now, considering that callbacks will not be triggered:
$this->Menus->updateAll(['css' => $menucss], ['id' => $menu_id]);
The other answers don't use internationalization and other models props, callbacks, etc.
I think this is because of the query builder, it does not use the models and so their behaviors, therefore you should use:
$this->loadModel('Inputs');
$input = $this->Inputs->find()->where(['`key`' => $this->request->data['id']])->first();
$this->Inputs->patchEntity($input, ['prop' => $this->request->data['prop']]);
if ($this->Inputs->save($input)) {
die(json_encode(true));
} else {
die(json_encode(false));
}

Categories