Codeigniter Update Multiple Records with different values - codeigniter

I'm trying to update a certain field with different values for different records.
If I were to use MySql syntax, I think it should have been:
UPDATE products
SET price = CASE id
WHEN '566423' THEN 49.99
WHEN '5681552' THEN 69.99
END
WHERE code IN ('566423','5681552');
But I prefer to use Active Record if it's possible.
My input is a tab delimited text which I convert into an array of the id and the desired value for each record:
$data = array(
array(
'id' => '566423' ,
'price' => 49.99
),
array(
'id' => '5681552' ,
'price' => 69.99
)
);
I thought this is the proper structure for update_batch, but it fails. Here's what I've tried:
function updateMultiple()
{
if($this->db->update_batch('products', $data, 'id'))
{
echo "updated";
}
else
{
echo "failed )-:";
}
}
And I get failed all the time. What am I missing?

Related

How to use where condition in update batch in Codeigniter

I want to update a multiple row using
$this->db->update_batch('mytable', $data);
But Don't Know How to give condition in this update_batch. Can I use this where?
$this->db->where('id', Multiple Ids Here);
i have code that is different from yours but it works and also it is easy to understand first put this function in your model file
in model file
function updatedata($tbname, $data, $parm)
{
return $this->db->update($tbname, $data, $parm);
}
in your controller file use like this
$this->load->model("Your_model_name");
$this->Your_model_name->updatedata('mytable',$data,$your_condition_in_array);
i hope this will help, i am sure about that this code works, please let me know that this code is worked for you.
Per the CodeIgniter documentation on update_batch()
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->update_batch('mytable', $data, 'title');
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
In other words, The array contains all data for the fields to be updated plus the item used to define the "where" condition. In the above arrays the value associated with the "title" key is used. So two records are updated: One where title = 'My title' and the second where title = 'Another title'
update_batch() returns the number of rows affected.

Laravel insert or update multiple rows

Im new in laravel, and im trying to update my navigation tree.
So i want to update my whole tree in one query without foreach.
array(
array('id'=>1, 'name'=>'some navigation point', 'parent'='0'),
array('id'=>2, 'name'=>'some navigation point', 'parent'='1'),
array('id'=>3, 'name'=>'some navigation point', 'parent'='1')
);
I just want to ask - is there posibility in laravel to insert(if new in array) or update my current rows in database?
I want to update all, because i have fields _lft, _right, parent_id in my tree and im using some dragable js plugin to set my navigation structure - and now i want to save it.
I tried to use
Navigation::updateOrCreate(array(array('id' => '3'), array('id'=>'4')), array(array('name' => 'test11'), array('name' => 'test22')));
But it works just for single row, not multiple like i tried to do.
Maybe there is another way to do it?
It's now available in Laravel >= 8.x
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 columns that should be updated if a matching record already exists in the database:
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);
I wonder why this kind of feature is not yet available in Laravel core (till today). Check out this gist The result of the query string would look like this: here
I am putting the code here just in case the link breaks in the future, I am not the author:
/**
* 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 );
}
So you can safely have your arrays inserted or updated as:
insertOrUpdate(
array(
array('id'=>1, 'name'=>'some navigation point', 'parent'='0'),
array('id'=>2, 'name'=>'some navigation point', 'parent'='1'),
array('id'=>3, 'name'=>'some navigation point', 'parent'='1')
)
);
Just in case any trouble with the first line in the function you can simply add a table name as a second argument, then comment out the line i.e:
function insertOrUpdate(array $rows, $table){
.....
}
insertOrUpdate(myarrays,'MyTableName');
NB: Be careful though to sanitise your input! and remember the timestamp fields are not touched. you can do that by adding manually to each arrays in the main array.
I've created an UPSERT package for all databases: https://github.com/staudenmeir/laravel-upsert
DB::table('navigation')->upsert(
[
['id' => 1, 'name' => 'some navigation point', 'parent' => '0'],
['id' => 2, 'name' => 'some navigation point', 'parent' => '1'],
['id' => 3, 'name' => 'some navigation point', 'parent' => '1'],
],
'id'
);
Eloquent Style
public function meta(){ // in parent models.
return $this->hasMany('App\Models\DB_CHILD', 'fk_id','local_fk_id');
}
.
.
.
$parent= PARENT_DB::findOrFail($id);
$metaData= [];
foreach ($meta['meta'] as $metaKey => $metaValue) {
if ($parent->meta()->where([['meta_key', '=',$metaKey]] )->exists()) {
$parent->meta()->where([['meta_key', '=',$metaKey]])->update(['meta_value' => $metaValue]);
}else{
$metaData[] = [
'FK_ID'=>$fkId,
'meta_key'=>$metaKey,
'meta_value'=> $metaValue
];
}
}
$Member->meta()->insert($metaData);
No, you can't do this. You can insert() multiple rows at once and you can update() multiple rows using same where() condition, but if you want to use updateOrCreate(), you'll need to use foreach() loop.
I didn't find a way to bulk insert or update in one query. But I have managed with only 3 queries. I have one table name shipping_costs. Here I want to update the shipping cost against the shipping area. I have only 5 columns in this table id, area_id, cost, created_at, updated_at.
// first get ids from table
$exist_ids = DB::table('shipping_costs')->pluck('area_id')->toArray();
// get requested ids
$requested_ids = $request->get('area_ids');
// get updatable ids
$updatable_ids = array_values(array_intersect($exist_ids, $requested_ids));
// get insertable ids
$insertable_ids = array_values(array_diff($requested_ids, $exist_ids));
// prepare data for insert
$data = collect();
foreach ($insertable_ids as $id) {
$data->push([
'area_id' => $id,
'cost' => $request->get('cost'),
'created_at' => now(),
'updated_at' => now()
]);
}
DB::table('shipping_costs')->insert($data->toArray());
// prepare for update
DB::table('shipping_costs')
->whereIn('area_id', $updatable_ids)
->update([
'cost' => $request->get('cost'),
'updated_at' => now()
]);
in your controller
use DB;
public function arrDta(){
$up_or_create_data=array(
array('id'=>2, 'name'=>'test11'),
array('id'=>4, 'name'=>'test22')
);
var_dump($up_or_create_data);
echo "fjsdhg";
foreach ($up_or_create_data as $key => $value) {
echo "key ".$key;
echo "<br>";
echo " id: ".$up_or_create_data[$key]["id"];
echo "<br>";
echo " Name: ".$up_or_create_data[$key]["name"];
if (Navigation::where('id', '=',$up_or_create_data[$key]["id"])->exists()) {
DB::table('your_table_ name')->where('id',$up_or_create_data[$key]["id"])->update(['name' => $up_or_create_data[$key]["name"]]);
}else{
DB::insert('insert into your_table_name (id, name) values (?, ?)', [$up_or_create_data[$key]["id"], $up_or_create_data[$key]["name"]]);
}
}

CakePHP Validate a specific rule only when a couple required fields aren't empty

I wrote a custom rule method for validating whether a record exists in the DB before adding a new record. I put the method in a behavior so I could share it with other models, but I've run into a chicken and egg situation.
In order to know whether a category has a specific group name already I need to have the category id, and the group name. So I pass those keys through using my custom rule (category_id and name). But, this won't work since if I don't choose a category_id by mistake then the query will occur on just the name, so I patched this with a couple lines, but need to return true if this is the case and bank on the category_id validation being invalid.
Is there a better way to implement this kind of validation? Is this not as bad as I think? Or just don't bother and in my controller drop hasAny() under my call to validates() if it passes.
MODEL:
public $validate = [
'category_id' => [
'rule' => 'notEmpty',
'message' => 'Category is required.'
],
'name' => [
'notEmpty' => [
'rule' => 'notEmpty',
'message' => 'Team is required.'
],
'recordExists' => [
'rule' => [ 'recordExists', [ 'category_id', 'name' ] ],
'message' => 'Group already exists.'
]
]
];
// BEHAVIOR:
public function recordExists( Model $Model, $conditions, $requireKeys )
{
// Overrite conditions to
$conditions = $Model->data[ $Model->name ];
// Trim all array elements and filter out any empty indexes
$conditions = array_map( 'trim', $conditions );
$conditions = array_filter( $conditions );
// Get the remaining non-empty keys
$conditionKeys = array_keys( $conditions );
// Only query for record if all required keys are in conditions
if (empty( array_diff( $requireKeys, $conditionKeys ) )) {
return !$Model->hasAny( $conditions );
}
// NOTE: seems wrong to return true based on the assumption the category_id validation has probably failed
return true;
}
Use the beforeValidate() callback of the model to check if the fields are present and if they're empty. If they're empty just unset() the recordExists validation rule in your models validation property. Copy them to a temporary variable or property in the case you want to set them back after your current operation.
And use $Model->alias, name will break if the model is used through an association that has a different name.
$conditions = $Model->data[ $Model->name ];

Codeigniter - Sending a query result_arry() to a View for form_dropdown

I am using form_dropdown() and have a a problem below:
The form code is:
echo form_dropdown($level,$level_options,'1');
It works when I use
$level_options = array(
'1' => 'Grade 6',
'2' => 'Grade 7'
);
but not when I send a $data['levels'] from controller to view
For reference, the model database retrieve code is:
public function getAllLevelNames() {
$query = $this->db->query("SELECT level_description from levels ORDER BY level_description");
return $query->result_array();
}
The Problem
The problem is I get a dropdown pick list with:
0
Grade 6
1
Grade 7
The indexes are greyed out.
How do I get rid of the indexes?
Thanks in advance!
P.S.
I seem to have the form working now with a data['levels'] sent to the view. Now, the following code in my view seems to return "null" to my controller. Any ideas why please?
$level = array(
'name' => 'level',
'id' => 'level',
'value' => '1',
'maxlength' => '50',
'size' => '50',
'style' => 'width:50%',
);
$level_options = $levels;
echo "<p>Level: ";
echo form_dropdown($level,$level_options,'1');
Thanks!
You'll need to loop through your results_array and create a new array which is formatted correctly.
$query = $this->db->query("SELECT level_description from levels ORDER BY level_description");
$for_dropdown = array();
foreach ($query->result_array() as $row) {
$for_dropdown[$row->level_description] = $row->level_description;
}
return $for_dropdown;
Also I'm not sure how your levels table is structured, but usually you'll have an ID of some sort, which will be the primary key. If you do have that, you can include it in your query and have something like this instead:
$query = $this->db->query("SELECT id, level_description from levels ORDER BY level_description");
... // other code
$for_dropdown[$row->id] = $row->level_description;

Filtering a text-type column with MySQL-computed values in Magento Admin Grid

Say one column in grid has computed values:
setCollection():
'refunded' => new Zend_Db_Expr("IF(qty_refunded > 0, 'Yes', 'No')"),
_prepareColumns():
$this->addColumnAfter('refunded', array(
'header' => Mage::helper('helper')->__('Refunded'),
'index' => 'refunded',
'type' => 'text',
), 'qty');
What and how must one change in order to have columns with "yes" values, in case admin types "yes" then filters?
Adminhtml grid columns have a filter property which specifies a block class. For boolean yes/no fields that would usually be adminhtml/widget_grid_column_filter_select.
It would be used automatically if your field type would be 'options'.
Try this in _prepareCollection():
'refunded' => new Zend_Db_Expr("IF(qty_refunded > 0, 1, 0)"),
And in _prepareColumns() use:
$this->addColumnAfter('refunded', array(
'header' => Mage::helper('helper')->__('Refunded'),
'index' => 'refunded',
'type' => 'options',
'options' => array(0 => $this->__('No'), 1 => $this->__('Yes'))
), 'qty');
This should still render your values as "Yes" and "No" in the Column, and you would get the select with the appropriate options as a filter dropdown.
This alone won't be enough since the column with the computed value can't be referenced directly in the WHERE clause by MySQL. Magento provides two options to work around that.
Column filter blocks have a method getCondition() which return a condition that will be used to filter the collection. See Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Abstract::getCondition() for an example.
So if you need to customize the SQL used to execute the filter, create your own column filter block extending Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Select and adjust the returned condition as needed, i.e. use the same computed value to match against.
Your custom filter can be specified for the column like this in the addColumn() definition:
'type' => 'options',
'options' => array(0 => $this->__('No'), 1 => $this->__('Yes')),
'filter' => 'your_module/adminhtml_widget_grid_column_filter_custom',
If you prefere to work outside of the limitations of Magento's ORM filter syntax, you can modify the collections select directly by using a filter callback:
'type' => 'options',
'options' => array(0 => $this->__('No'), 1 => $this->__('Yes')),
'filter_condition_callback' => array($this, '_applyMyFilter'),
The callback receives the collection and the column as arguments. Here is a simple example for that method:
protected function _applyMyFilter(Varien_Data_Collection_Db $collection, Mage_Adminhtml_Block_Widget_Grid_Column $column)
{
$select = $collection->getSelect();
$field = $column->getIndex();
$value = $column->getFilter()->getValue();
$select->having("$field=?, $value);
}
Needless to say that both approaches (filtering against the computed value) is very inefficient in MySQL. But maybe that's no a problem for you in this case.
I'll post a working example, but I'll choose Vinai's answer for being so detailed.
In Grid.php:
protected function _addColumnFilterToCollection($column)
{
if ($column->getId() == 'refunded' && $column->getFilter()->getValue()) {
$val = $column->getFilter()->getValue();
$comparison = ($val === "No") ? 'lteq' : 'gt'; // lteg: <=; gt: >
$this->getCollection()->addFieldToFilter('ois.qty_refunded', array($comparison => 0));
} else {
parent::_addColumnFilterToCollection($column);
}
return $this;
}

Resources