my target is to total all the (commtype = IN) betAmount only and store it on my "comCurrentBalance" users table. Then, with my SQL update it'll be subtracted the user input's amount to the total value of betAmount from "agent_commmission_history" table. I provided a screenshot below for my problem and my target. Any help will be appreciated.
Controller:
public function comm($userID=0) {
$this->commissions->commOut($userID);
redirect(base_url() . "commission/commi");
}
Model:
function commOut($data) {
$ref= $this->session->userdata('uid') + date ('his');
$id = $this->session->userdata('uid');
$data = array(
'userID' => $id,
'transactionSource' => 'Commi',
'refNumber' => $ref ,
'amount' =>$this->input->post("amount"),
"transType" =>"out",
);
$sqlInsertLedger = "INSERT INTO transaction_ledger (transactionSource, transType, refNumber, userID, amount, currentBalance, previousBalance, remarks, createdBy)
select '".$data['transactionSource']."', '".$data['transType']."', '".$data['refNumber']."', ".$data['userID'].", ".$data['amount'].", sum(TU.currentPoints + ".$data['amount'].") as totalPoints, TU.currentPoints,
'funded by agent', '".$this->session->userdata('uid')."'
from users TU where TU.userID=?";
$Q = $this->db->query($sqlInsertLedger, $data['userID']);
//update user table
$sqlUpdate = "update users set commCurrentBalance = commCurrentBalance - ?, currentPoints = currentPoints + ? where userID = ?"; // ***Current points is already adding and comCurrentBalance is subtracting based on user's input. However, my target is to total the betamount before subtracting happens.*****
$Q = $this->db->query($sqlUpdate, array($data['amount'], $data['amount'], $data['userID']));
}
Related
I am trying to write code to return the number of diseases diagnosed in a clinic after a given period either weekly, monthly or daily using jimmyjs laravel-report-generator using the code bellow,
$fromDate = $request->fromDate;
$toDate = $request->toDate;
$sortBy = 'updated_at';
$title = 'CHATTHE GROUP'; // Report title
$subTitle = 'Mobidity Report';
$total = 0;
$meta = [ // For displaying filters description on header
''=> $subTitle,
'From' => $fromDate . ' To: ' . $toDate,
'Generated By' => Auth::user()->name
];
$queryBuilder = Diagnosis::select(['diagnosis', 'updated_at']) // Do some querying..
->whereBetween('updated_at', [$fromDate, $toDate])
->distinct('diagnosis')
->orderBy($sortBy, 'ASC');
$columns = [ // Set Column to be displayed
'DISEASE' => 'diagnosis',
'NO OF CASES' => function($result){
return Diagnosis::where('diagnosis',$result->diagnosis)->count();
}, // if no column_name specified, this will automatically seach for snake_case of column name (will be registered_at) column from query result
'% TOTAL' => function($result){
return (Diagnosis::where('diagnosis',$result->diagnosis)->count()/$result->count()*100);
}
];
return ExcelReport::of($title, $meta, $queryBuilder, $columns)
->editColumns(['DISEASE', '% TOTAL'], [ // Mass edit column
'class' => 'right bold'
])
->showHeader(true)
->simple()
->download('mobidityReport');
This produces the following excel file
Which has the diseases repeated just as they repeat in the table, is there anyway to avoid this? I tried using distinct() but that gave an error.
I want update or create in data base
but i want get the old value and updated value because i want to compare between these two value
for example
this item in table user
name = Alex and Order = 10
so now i want update this person by
name = Alex and Order = 8
Now After updating or creating if not exist
just for update i want get
Old order 10 | And new Order 8
I want compare between these order
i have tryin getChange() and getOriginal() but two the function give me just the new value.
Please Help
You can get the old value using getOriginal if you have the object already loaded.
For example :
$user = User::find(1);
$user->first_name = 'newname';
// Dumps `oldname`
dd($user->getOriginal('first_name'));
$user->save();
However in case of updateOrCreate, you just have the data. I am not sure about a way to do it using updateOrCreate but you can do simply do :
$user = User::where('name', 'Alex')->first();
$newOrder = 10;
if($user){
$oldOrder = $user->getOriginal('order');
$user->order = $newOrder;
$user->save();
}
Is the name unique in the table? Because if it is not you will have updates on multiple rows with the same data.
So the best approach is to use the unique column which is probably the ID.
User::updateOrCreate(
[ 'id' => $request->get('id') ], // if the $id is null, it will create new row
[ 'name' => $request->get('name'), 'order' => $request->get('order') ]
);
Solution
$model = Trend::where('name', $trend->name)->first();
if ($model) {
$model->old_order = $model->getOriginal('order');
$model->order = $key + 1;
$model->save();
} else {
Trend::where('order', $key + 1)->delete();
$new = new Trend();
$new->name = $trend->name;
$new->old_order = $key + 1;
$new->order = $key + 1;
$new->tweet_volume = $trend->tweet_volume;
$new->save();
}
This code enters multiple products in orders table, but what strange thing is happening is if i insert 2 products, data is being entered 4 times, if i insert 1 product it is being inerted 2 times. What is wrong with this code ?
foreach($request->product_id as $rpk => $rpv)
{
$data = new Order();
$data->user_id = $request->customer_id[$rpk];
$data->status = $request->status[$rpk];
$data->save();
Order::where('id', $data->id)->update(['order_number' => $data->id]);
// For OrderDetail
$detail = new OrderDetail();
$detail->customer_id = $request->customer_id[$rpk];
$detail->order_id = $data->id;
$detail->product_id = $request->product_id[$rpk];
$detail->price = $request->price[$rpk];
$detail->quantity = $request->quantity[$rpk];
$detail->total = $request->total[$rpk];
$detail->comment = $request->comment[0];
$detail->date = date('Y-m-d H:i:s');
$detail->bill_date = date('Y-m-d H:i:s');
//$detail->sales_tax = '13'; // Need to change this
$success = $detail->save();
}
I was learning about How to insert multiple rows from a single query using eloquent/fluent and I found the answer here
Can somebody share any documentation about how to update bulk rows in single query?
My queries are below.
Update tblrole set role = 'Super Admin' where RoleID = 1;
Update tblrole set role = 'Super Admin A' where RoleID = 2;
Update tblrole set role = 'Super Admin B' where RoleID = 3;
Update tblrole set role = 'Super Admin C' where RoleID = 4;
You can solve the issue using a single MySQL query. It can be implemented in Laravel Eloquent using DB::raw() method.
**UPDATE** tblrole **SET** role =
**CASE**
WHEN RoleID = 1 THEN 'Super Admin'
WHEN RoleID = 2 THEN 'Super Admin A'
WHEN RoleID = 3 THEN 'Super Admin B'
WHEN RoleID = 4 THEN 'Super Admin C'
**END**
**WHERE** RoleID in (1,2,3,4);
You cannot do anything like this in simple way. You can easily update multiple rows with same value but if you want to update role column with different values it will be tricky.
In fact it doesn't make much sense to do it like this but if you really want it and you think it's the best solution you can try to play with raw queries using technique described here https://stackoverflow.com/a/25674827/3593996
You might find inspiration from this mass insert or update gist:
/**
* Mass (bulk) insert or update on duplicate for Laravel 4/5
*
* insertOrUpdate([
* ['id'=>1,'value'=>10],
* ['id'=>2,'value'=>60]
* ]);
*
*
* #param array $rows
*/
function insertOrUpdate(array $rows){
$table = \DB::getTablePrefix().with(new self)->getTable();
$first = reset($rows);
$columns = implode( ',',
array_map( function( $value ) { return "$value"; } , array_keys($first) )
);
$values = implode( ',', array_map( function( $row ) {
return '('.implode( ',',
array_map( function( $value ) { return '"'.str_replace('"', '""', $value).'"'; } , $row )
).')';
} , $rows )
);
$updates = implode( ',',
array_map( function( $value ) { return "$value = VALUES($value)"; } , array_keys($first) )
);
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}";
return \DB::statement( $sql );
}
Ref: https://gist.github.com/RuGa/5354e44883c7651fd15c
I don't think I need to provide any explanation as each chunk of code in the function speaks of itself.
I have a function that runs raw SQL queries to our database in Magento. What the function does is changes the customer's default credit card to a value passed to the function. My question is how would I rewrite the function utilizing Magento models. The current function works, but we'd rather have it not be directly interfacing with SQL.
Here is the function:
public function setDefaultPayment($value)
{
$customerId = $this->_getSession()->getCustomer()->getId();
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$read = $write->query("SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code='customer'");
$row = $read->fetch();
$entity_type_id = $row['entity_type_id'];
$read = $write->query("SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_payment' AND entity_type_id = $entity_type_id");
$row = $read->fetch();
$attribute_id = $row['attribute_id'];
$read = $write->query("SELECT * FROM customer_entity_int WHERE entity_type_id='$entity_type_id' AND attribute_id='$attribute_id' AND entity_id='$customerId'");
if ($row = $read->fetch()) {
$write->update(
'customer_entity_int',
array('value' => $value),
"entity_type_id='$entity_type_id' AND attribute_id='$attribute_id' AND entity_id='$customerId'"
);
} else {
$write->insert(
'customer_entity_int',
array(
'entity_type_id' => $entity_type_id,
'attribute_id' => $attribute_id,
'entity_id' => $customerId,
'value' => $value
)
);
}
}
If I read you code right, you want to update the customer attribute default_payment with a value given.
For that you need to:
Load the customer by id
Set the new value for the customer attribute default_payment
Save the customer
public function setDefaultPayment($value)
{
$customerId = $this->_getSession()->getCustomer()->getId();
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$customer = Mage::getModel('customer/customer')->load($customerId);
$oldValue = $customer->getDefaultPayment(); // optional, just for checking
$customer->setDefaultPayment($value);
$customer->save();
}