Batch_update primary key joining table - codeigniter

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.

Related

How to access array value of count

How do I access the value of the array of COUNT(*)? I get the error Cannot use object of type stdClass as array when i tried to use $availableRooms[3]['COUNT(*)']
Array
(
[0] => stdClass Object
(
[category] => king
[COUNT(*)] => 3
)
[1] => stdClass Object
(
[category] => family
[COUNT(*)] => 7
)
[2] => stdClass Object
(
[category] => quad
[COUNT(*)] => 8
)
[3] => stdClass Object
(
[category] => standard
[COUNT(*)] => 7
)
)
I need to get the value of count. In this case when i use $availableRooms[3]['COUNT(*)'] it should output 7
**EDIT**
Query
$availableRooms = DB::select("SELECT
category, COUNT(*)
FROM available_rooms
WHERE NOT EXISTS (
-- room is booked on the requested dates (...not)
SELECT 1
FROM room_reserveds
JOIN bookings ON room_reserveds.bookingID = bookings.bookingID
WHERE room_reserveds.roomID = available_rooms.roomID
AND $checkOutDate > checkIndate
AND $checkInDate < checkOutDate
)
GROUP BY category");
The array contains objects, so you can't use the array notation to get these properties. And because it's a special key, you can get the property by placing the name between {} as a string.
$availableRooms[3]->{'COUNT(*)'};
I suppose this results comes from a database query. A better solution would be to give this result an alias that can be referenced directly.
// SQL:
SELECT COUNT(*) AS count FROM ...
// PHP:
$availableRooms[3]->count;

Want to Join Two table without Knowing other Table Name Laravel

$users = DB::table('table1')->where('id', '=', '1')->get();
$joinedtable = DB::table('table1')
->join('' . $users[0]->tablename . '', 'table1.id', '=', '' . $users[0]->tablename . '.id')
->get();
I want to join two table, 1st table name is given and 2nd is comming from table1. I want to short this query and want to done using one query. Is it possible
Current O/P
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 1
[country] => table2
[test1] => 23423
[test2] => 234234
[newdata1] => 1
[newdata2] => 1
[newdata3] => 1
)
[1] => stdClass Object
(
[id] => 2
[country] => table3
[test1] => 123
[test2] => 123
[newdata1] => 2
[newdata2] => 2
[newdata3] => 2
)
)
First solution Option
Use pluck() to get the table name and then join the tables.
$table2 = DB::table('table1')->where('id', '=', '1')->pluck('columnname');

Laravel - Hide model properties in collection

Is there a way to hide the properties of a model, like table, connection, primaryKey, etc in a Laravel collection and keep only the attributes/columns of the table?
[table:protected] => product
[connection:protected] => mysql
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
...
)
[original:protected] => Array
(
...
)
...
)
You don't need to do that because these are properties of an Eloquent model object and they will be ignored when you'll serialize the object or convert it to JSON or an array:
$model->toArray()

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,
]);

laravel querying database not producing expected results

I'm trying to execute this sql query using laravel query builder.
SELECT leagues.id, leagues.name, countries.name
FROM leagues
INNER JOIN countries ON leagues.country = countries.id
I have the following Laravel query...
$leagueinfo = DB::table('leagues')
->join('countries','leagues.country', '=', 'countries.id')
->select('leagues.id', 'leagues.name', 'countries.name')
->get();
but when I print_r($leagueinfo) out to the screen I get this...
Array ( [0] => stdClass Object ( [id] => 1 [name] => England ) [1] => stdClass Object ( [id] => 2 [name] => Spain ) [2] => stdClass Object ( [id] => 3 [name] => Italy ) [3] => stdClass Object ( [id] => 4 [name] => Austria ) [4] => stdClass Object ( [id] => 5 [name] => Germany ) [5] => stdClass Object ( [id] => 6 [name] => England ) )
.. which looks like it's picking up my countries only.
The sql query returns the correct results... the league.id, league.name and the countries.name
Would anyone have any suggestions why the information is not coming through, please?
Thanks.
DS
If you look at your result set, you actually have the ID as well. What's happening is you're overwriting your column name in the result set since two fields are both "name". Try the following instead:
$leagueinfo = DB::table('leagues')
->join('countries','leagues.country', '=', 'countries.id')
->select('leagues.id', 'leagues.name as league', 'countries.name as country')
->get();

Resources