Reputation: 1184
I can't figure out how to set a field to null on certain condition. It should be an easy query but I'n not able to set the right value for NULL on a nullable field.
Product::where('id', $product_list)->update(['family_id' => null]);
nor
Product::where('id', $product_list)->update(['family_id' => DB::raw(null)]);
did the trick. Both cases compiled fine but the generated query seems to be wrong because I get a SQL error. In the irst case the error is :
SQLSTATE[HY093]: Invalid parameter number (SQL: update `products` set `family_id` = ?, `products`.`updated_at` = 2019-11-12 08:41:07 where `id` = ?)
and the error for the second one is :
QLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ', `products`.`updated_at` = ? where `id` = ?' at line 1 (SQL: update `products` set `family_id` = , `products`.`updated_at` = 2019-11-12 08:21:50 where `id` = ?)
In the first case it seems that NULL is not being added to the parameters to the prepared query, and in the secon the NULL value is being inserted as nothing in the query. There is any simple way to set the value to NULL?
Upvotes: 3
Views: 6509
Reputation: 1
Try this
Product::where('id', $product_list)->update(['family_id' => 'NULL']);
Upvotes: 0
Reputation: 1
The DB::raw()
requires a string of 'NULL'
to work properly:
Product::where('id', $product_list)->update(['family_id' => DB::raw('NULL')]);
Upvotes: 0
Reputation: 2945
You should consider the following things first.
1) family_id
column is nullable in your table. if not then set nullable.
2) Make sure you have in $fillable
property of Product
model column family_id
.
Make sure $product_list
returns id
of that particular product.
if $product_list
is collection/array of product data then use like:
Product::where('id', $product_list->id)->update(['family_id' => null]);
Upvotes: 5