Model::create($dataarray) removes random row of data - php

I am using laravel's Model::create() function to create a new entry in my database, but the array i'm passing into the function fails because it deletes one of the rows.
This is my array All static. This also matches what my database table looks like.
$data = [
'terminal_id' => 222,
'batch_id' => 1,
'transactiondate' => '2323',
'store' => '2323',
'hostcode' => '2323',
'pan' => '2323',
'operation' => '2323',
'posdatacode' => '2323',
'amount' => '2323',
'currency' => '2323',
'acquirer' => '2323',
'scheme' => '2323',
'attemptsconn' => '2323',
'transactionresult' => '2323',
'merchantcode' => '2323',
'terminal' => '2323'
];
And the line to insert it into the database
Transaction::create($data);
SQL error code when running this code:
SQLSTATE[HY000]: General error: 1364 Field 'amount' doesn't have a default value (SQL: insert into `transactions` (`terminal_id`, `batch_id`, `transactiondate`, `store`, `hostcode`, `pan`, `operation`, `posdatacode`, `currency`, `acquirer`, `scheme`, `attemptsconn`, `transactionresult`, `merchantcode`, `terminal`, `updated_at`, `created_at`)
Now, if you look through the code, you'll notice the amount section of the array has gone missing.
What have i tried:
Formatting the entry code to Transaction::create(['row' => 'value']) instead of what i was doing. This returns same result.
Creating a new transaction by doing new Transaction and then $transaction->value to insert the data. THIS WORKS.
I must be missing something obvious since this doesn't work. Please help me out.

Error:
"Field 'amount' doesn't have a default value"
comes due to
you can not set a default value for amount field in the database when the field amount is missing from the array, error throw.
So set the default value or set Null.

As Liam suggested the "amount" field was not in my $fillable array in the Model.
Code works flawlessly after inserting that value into the array.
Please upvote Liam's comment if you had an error like this, no need to answer this further.

Related

AWS Dynamodb Scan | Scan if exists column values

I have a table that has a column called "items", but not all rows have it, so I want to scan all rows that have "items".
Something like:
$resposta = $clientDB->scan(array(
'TableName' => 'tableName',
'Key' => [
'items' => ['S' => 'exists']
]
));
But I can't figure out how to do it...
The table has 10000 rows, but only 10 of them have "items", and I want to get only these 10 rows.
Edit:
As Seth Geoghegan pointed below, it was necessary create a global secondary indexes on the attribute i wanted to filter.
I ended up here:
$params = [
'TableName' => 'tableName',
'FilterExpression' => "attribute_exists(items)"
];
OR
$params = [
'TableName' => 'tableName',
'FilterExpression' => 'items != :null',
'ExpressionAttributeValues' => [
':null' => null,
],
];
But both didnt worked... First one seens necessary ExpressionAttributeValues to be setup and the second the php stop working with no error logs.
This is a perfect use case for global secondary indexes (GSI)!
You can create a GSI on the items attribute. Items with the items attribute defined will get projected into the GSI. Importantly, items that do not contain this attribute will not be in the index. You could then query the GSI and retrieve the items you're after.
Well, after some effort, i found a way though:
$resposta = $clientDB->scan(array(
'TableName' => 'tableName',
'FilterExpression' => "attribute_exists(items)"
));
After i created another global secondary index (GSI) for "items" (pointed by Seth Geoghegan), i just needed to add in the scan function the FilterExpression the "attribute_exists(items") and it worked.

Laravel 8 update JSON column value

I'm trying to update the value of a json column type for all of my users, my query that I'm running through Tinker doesn't give any errors, it just returns 0 and the columns remain unchanged, what am I doing wrong?
User::where('notification_preferences')->update(['notification_preferences' => [
'domains' => [
'expiry' => [
'mail' => true,
'database' => true
]
]
]])
My columns on my rows currently has the value of...
{
"expiry_alerts": true
}
After I have read the comment below it came clear to me that you used the wrong syntax for the WHERE query of a JSON column. You have to use the -> operator.
For further information please see https://mattstauffer.com/blog/new-json-column-where-and-update-syntax-in-laravel-5-3/
&
https://laravel.com/docs/8.x/queries#json-where-clauses
It should work like this:
User::where('notification_preferences->expiry-alerts',true)->update(['notification_preferences' => [
'domains' => [
'expiry' => [
'mail' => true,
'database' => true
]
]
]])
I think the problem is your where clause User::where('notification_preferences'), if you express this to sql User::where('notification_preferences')->toSql(), you will notice something like this
from users where notification_preferences is null..., probably this is the reason why the update is not executed.

Laravel firstOrCreate with relationships not returning a model instance

I am using firstOrCreate() to find the first invoice or create it.
This code was working last week then all of a sudden stopped working.
What is working:
A database entry IS generated & there are no errors.
The problem: firstOrCreate returning empty. {}
The code:
$invoice = Invoice::firstOrCreate(
[
'user' => $user->id,
'package' => $package->id,
'term' => $pricing->term,
'paid' => 0
], [
'amount' => $pricing->price,
'hash' => 'omittedforSO',
'coupon' => null
]
)->with(['billingInfo', 'package', 'price', 'coupon']);
You have to call with() before firstOrCreate()
$invoice = Invoice::with(['billingInfo', 'package', 'price', 'coupon'])->firstOrCreate(
[
'user' => $user->id,
'package' => $package->id,
'term' => $pricing->term,
'paid' => 0
], [
'amount' => $pricing->price,
'hash' => 'notforSO',
'coupon' => null
]
);
According to firstOrCreate and your eager loading, he should either find and return the first model of Invoice where the arguments (first array) match with extra attributes as arrays, containing the relationships you've written, or create an Invoice with the values of your second argument.
Having that said, it shouldn't return an empty array, ever, unless you've edited Laravel's core code. If you var_dump (dd) that result ($invoice), it will either give you a Querybuilder or an Eloquent model (with its list of attributes with null values).
Make sure your fields are in the fillable array of the model Invoice

DynamoDB updateItem creates new record

Its updating data if session is exists fine.
But when session is not exists its create a new row.At this stage , i dont want to do any action.
$sessionId = $params['session_id'];
$response = $this->dbo->updateItem([
'TableName' => $this->tableName,
'Key' => [
'id' => [ 'S' => $sessionId]
],
'ExpressionAttributeValues' => [
':val1' => ['S' => date('Y-m-d H:i:s')]
],
'UpdateExpression' => 'set sessionEnd = :val1',
'attributeExists' => 'id',
'ReturnValues' => "UPDATED_NEW"
]);
The update item API would create the new item if it doesn't exist. You can use ConditionExpression to stop creating the new item.
Edits an existing item's attributes, or adds a new item to the table
if it does not already exist.
This means only if the id is already present, the update operation will happen. Also, it will stop creating the new item.
'ConditionExpression' => 'attribute_exists(id)',
If the key is not found, the API throws the below exception.
"code": "ConditionalCheckFailedException",

Dynamodb update table data not working

I want to update data using 'typeId', 'type_id' is not a primary key.
While this code is work, if we use other primary key.
Unable to update record.
getting following error :
{"__type":"com.amazon.coral.validate#ValidationException","message":"The provided key element does not match the schema"}
$response = $this->dbo->updateItem([
'TableName' => $this->tableName,
'Key' => [
'typeId' => ['S' => "qtwr234"]
],
'ExpressionAttributeValues' => [
':val1' => ['N' => '1']
],
'UpdateExpression' => 'set count = :val1',
'ReturnValues' => 'ALL_NEW'
]);
According the error message you're receiving
This error occurs when your key (hash / primary key) doesn't not match in parameters your passing to update the data in table.
Solution :
Run listTables commands and check for key element you created while creating elements.
Now, replace that key element in query parameters.
Thanks

Categories