Laravel query builder - bulk insert - Ignore columns not found - laravel

I am using laravel query builder where I am bulk inserting hundreds of rows. I want to insert the column found and ignore the columns not found in table
Here is my code:
$proposalOpsEvents = DB::table('table1')->where('proposal_id', $proposal->id)->get();
$proposalOpsEvents = $proposalOpsEvents->toArray();
DB::connection('mysql_archive')->table('archive_table1')->insert($proposalOpsEvents);
I get error "Unknown column".
In table 1 new columns are getting added dynamically. I want to ignore the newly added columns when inserting in archive_table1.
For example,
DB::table('archive_table1')->insert([
'email' => 'abc#example.com', //email column found - insert
'phone' => 0, // phone column found - insert
'address' => 'A'// address column (newly added) not found - ignore
]);
Any solution for these?

Have you tried the insertOrIgnore method?
DB::table('archive_table1')->insertOrIgnore([
'email' => 'abc#example.com', //email column found - insert
'phone' => 0, // phone column found - insert
'address' => 'A'// address column (newly added) not found - ignore
]);

You can use the DB::squemaBuilder
$columns=DB::connection('your_connection')->getSchemaBuilder()->getColumnListing('table_name');
This will return an array with all columns names of the table and with array manipulation you can intersect your columns to insert with columns in table.
$newData=[
'email' => 'abc#example.com', //email column found - insert
'phone' => 0, // phone column found - insert
'address' => 'A'// address column (newly added) not found - ignore
];
$newDataClean=array_intersect_key($newData, array_flip($columns));

Related

Join table multiple columns groupBy with count in Laravel

I'm trying to group joindraw table with count, but getting the following error. How can i get the count and group via multiple columns?
Controller
$joindraw_participants = Joindraw::where('product_id', $id)
->groupBy('user_id', 'created_at')
->with('user')->take(10)->desc()->get();
Error
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'yangmao.joindraw.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from joindraw where product_id = 1 group by user_id order by joindraw.created_at desc limit 10)
With strict mode enable groupBy needs all the columns in the select to be in groupBy also. To remove this validation either you can set strict => false in config/database.php for mysql or you can specify the modes so that other modes won't be affected. Like this:
'modes' => [
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
]
Put an empty array of modes to overwrite the default in your config/database.php file.
'mysql' => [
'modes' => [],
],

Batch insert in Laravel 5.2

I am using a API's with lot's of calculation almost 100 database fields at the end with a big Foreach loop.
In every iteration i insert data in database. I want to insert data in once at the end (Batch Insert like in CodeIgniter).
Any body have idea how to insert all data at the end of iteration. instead of every iteration it insert row in database.
I want to insert data at the end of loop. Any help or idea appreciated.
Use insert() method for bulk insertion. First, build an array with this structure:
$data = [
['name' => 'John', 'age' => 25],
['name' => 'Maria', 'age' => 31],
['name' => 'Julia', 'age' => 55],
];
Then insert the data using Eloquent model:
Model::insert($data);
Or using query builder:
DB::table('table_name')->insert($data);

Laravel save() is not update record

I am trying to update records in the database table if record already exists. Insert new record if record is not to the database table.
I have written below code for that
DB::enableQueryLog();
$user->userCommission()->save(new UserCommission($input['commission']));
dd(DB::getQueryLog());
when EnableQueryLog it's always show insert query, If record is already in the table.
Here is my query..
array:1 [▼
0 => array:3 [▼
"query" => "insert into `user_commissions` (`created_by`, `status_id`, `percent`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?)"
"bindings" => array:6 [▼
0 => "1"
1 => "1"
2 => "0.10"
3 => 21
4 => "2016-08-13 08:07:45"
5 => "2016-08-13 08:07:45"
]
"time" => 2.57
]
]
In above query user_id 21 record already in the table although Save() insert record to the database.
where am i wrong with this code?
May I have to apply unique key to the table?
Require at least one unique column to find or update table record
$userCommission = UserCommission::firstOrNew(array('created_by' => 1));
$userCommission->status_id = 1;
$user()->userCommission()->save($userCommission);
There is a alternative one way step to check this.update_at & created_at will be inserted by laravel default
userCommission::updateOrCreate([
'user_id' => 21
],[
'created_by' => 1,
'status_id' => 1,
'percent' => "0.10",
'user_id' => 21,
]);

show attribute value in admin magento

I am new in magento.
I added an extra field in sales_flat_order table i.e.,order_campaign_params
When a customer completed its order, data is inserting into this table.
Now i want to show this attribute value in admin.
I added an extra column in admin i.e., Order Utm Source but data is not showing.
Please tell me how to show the attribute value in admin.
Please see the code for adding column
$this->addColumn('order_campaign_params', array(
'header' => Mage::helper('orderreport')->__('Order Utm Source'),
'index' => 'order_campaign_params',
'filter_index'=>'customer_entity.order_campaign_params',
'width' => '70px',
));
But how to show data of that field, Please explain.
Please see the structure:
customer_entity_varchar table
value_id entity_type_id attribute_id entity_id value
136977 1 5 43120 Sanghamitra
136978 1 7 43120 samal
136979 1 12 43120 0860142023b7a810ce66a21b68
136980 1 174 43120 data(order_compaign_params)
136981 1 3 43120 Kalazone.in
Thanks
Sales order grid is build from sales_flat_order_grid table. The column order_campaign_params exists in sales_flat_order table and not sales_flat_order_grid table.
So you need to MySQL join with sales_flat_order_grid table sales_flat_order table like below:
$select = $collection->getSelect();
$select->joinLeft(array('order' => Mage::getModel('core/resource')->getTableName('sales/order')), 'order.entity_id=main_table.entity_id',
array('order_campaign_params' => 'order_campaign_params'));
$select->joinLeft(array('custeav' => 'customer_entity_varchar'), 'custeav.attribute_id=main_table.order_campaign_params', array('*'));
The order_campaign_params column will now be displayed in the grid.
Hope this helps.

Batch_update primary key joining table

i'm having a problem with batch update function with codeigniter, i'm using a joining table for my products and categories, as I have a many to many relationship. I have searched high and low for an answer but still nothing so i have come here to ask more senior technicians for help.
I have 2 columns in a table "product_category" with "product_id" & "category_id" so I can link 1 product to many categories. I have managed to perform the insert query which inserts all the id's fine, but the update is not working. Here's my code:
model:
function update_product_cat($product, $cat_id) {
$data = array();
foreach( $product as $index => $value )
{
$data[] = array(
'product_id' => $value ,
'category_id' => $cat_id[ $index ]
);
}
$this->db->update_batch('product_category', $data,
'product_id');
}
array:
Array ( [0] => Array ( [product_id] => 327 [category_id] => 3 ) [1] => Array ( [product_id] => 327 [category_id] => 5 ) [2] => Array ( [product_id] => 327 [category_id] => 7 ))
My error code:
Error Number: 1062
Duplicate entry '327-3' for key 'PRIMARY'
UPDATE product_category SET category_id = CASE WHEN product_id = '327' THEN '3' WHEN product_id = '327' THEN '5' WHEN product_id = '327' THEN '7' ELSE category_id END WHERE product_id IN ('327','327','327')
Any help would be greatly appreciated:
thanks
I'm not 100% sure this is your entire problem, but it looks like the product_category table has product_id set as a primary key - where it looks like you are trying to enter many identical product_id's. If that were the case you should probably just be using a regular update not batch, not to mention removing/replacing the primary key.

Resources