I am trying to save my Laravel Eloquent model to the database.
All date properties are saved in wrong format to DB (even created_at and updated_at).
In example below, my updated_at has been renamed as S_MODDATE but it's still the "native" field.
Reading the date fields works fine.
Example
My date in PHP : 2021-12-07 (7th of December)
When saved to database : 2012-07-12 (12th of July)
When read again from database : 2012-07-12
Minimal example of my code :
$currentDatetime = new \DateTime();
Log::debug($currentDatetime->format("Y-m-d h:i:s")); // Looks correct
$approRecord = T_Appro::find($approvalId);
$approRecord->DATESTATUT = $currentDatetime;
DB::enableQueryLog();
$approRecord->save();
Log::debug(DB::getQueryLog());
Corresponding log
[2021-12-07 13:17:25] local.DEBUG: 2021-12-07 01:17:25
[2021-12-07 13:17:28] local.DEBUG: array (
0 =>
array (
'query' => 'update [t_appro] set [DATESTATUT] = ?, [t_appro].[S_MODDATE] = ? where [T_APPROID] = ?',
'bindings' =>
array (
0 =>
DateTime::__set_state(array(
'date' => '2021-12-07 13:17:25.981319',
'timezone_type' => 3,
'timezone' => 'Europe/Brussels',
)),
1 => '2021-12-07 13:17:28.035',
2 => 'S000000029',
),
'time' => 468.81,
),
)
Tested solutions
Add protected $dateFormat = 'Y-m-d H:i:s'; to my model
Add following code to my model
public function getDateFormat()
{
return 'Y-m-d H:i:s.v';
}
Set app.php timezone to Europe/Brussels
Related
I am using Laravel Framework 6.16.0 and I am creating from a string a date object so that I can input it in my db:
$transaction_date = Carbon::createFromFormat('Y-m-d', $tradeDate);
$filling_Date = Carbon::createFromFormat('Y-m-d H:i:s', $fillingDate, 'UTC');
$product = Product::updateOrCreate(
[
'price' => trim($price),
'qty' => $qty,
'companies_id' => $company->id,
'persons_id' => $person->id,
'amount_range' => $owned,
'filling_date' => $filling_Date,
'transaction_date' => $transaction_date,
],
[]
);
When running the above query my product does not get found as $filling_Date and $transaction_date are not matched in the database, even if my product already exists.
I am guessing, the reason is that I am creating a "new" Carbon object.
Any suggestions how to match the filling_date and transaction_date in the database?
I appreciate your replies!
Try this when converting a string to a date with Carbon
$date = Carbon::parse($yourStringDate);
I want to use updateOrCreate in order to prevent duplicate
I have stores and need to store for every store its working hour (days, open time, close time, available)
Day Available Open Close
Monday [checkbox] [input] [input]
Tuesday [checkbox] [input] [input]
Wednesday [checkbox] [input] [input]
but I still get duplicate when inserting new values
Model:
protected $table = 'storedays';
protected $fillable = ['storeinfo_id', 'day_id','open_time','close_time','available'];
protected $primaryKey = 'id';
Controller:
public function store(Request $request)
{
$store_id=$request->storeinfo_id;
$open_time = $request->input('open_time');
$close_time = $request->input('close_time');
$available=$request->input('available');
foreach ($request->input('day_id') as $key => $value) {
if ( ! isset($available[$key])) {
$available[$key] = 0;
}
else
{
$available[$key] = 1;
}
Storeday::updateOrCreate([
'storeinfo_id' => $store_id,
'day_id' => $value,
'open_time' => $open_time[$key],
'close_time' => $close_time[$key],
'available' => $available[$key],
]);
}
return response()->json(['data' => trans('message.success')]);
}
updateOrCreate function requires 2 params, match conditions and extra values. You need to change it to following:
Storeday::updateOrCreate([
'storeinfo_id' => $store_id,
'day_id' => $value,
],[
'open_time' => $open_time[$key],
'close_time' => $close_time[$key],
'available' => $available[$key],
]);
What will the line do?
First it will look if there is an entry in table for the store id and day id. If not, it will create a new row.
You can learn more about the updateOrCreate function here.
I need to query the date:- 2020-01-06 If this date ( 2020-01-06 ) exists in the _from field in the post meta table.
_form field is in timestamp format like 1578304800.
This is how I am trying to do.
$theBookingTime = strtotime( '2020-01-06' );
$events_query = new WP_Query(
array(
'post_type' => array('yith_booking', 'post'),
'meta_query' => array(
array( 'key' => '_from',
'value' => date('c', $theBookingTime),
'compare' => '=',
'type' => 'DATETIME',
)
)
));
ADDING FOR INFO :_
And if we convert the time stamp "1578304800" to date it get 2020-01-06 10:00:00
And i need to compare only the date with the given timestamp in table field ( _form )>
I need to find the 2020-01-06 ** Only the date part from the date and time in the table**>>
If this can be done with the custom mysql also? please suggest.
You're using 'value' => date('c', $theBookingTime),
The 'c' corresponds to the output format of your date. What you're looking for is 'value' => date('Y-m-d', $theBookingTime), where Y will output the year in 4 digits, m will output the month and d - the day.
i'm newbie in Cake and wodering how to insert multiple rows in a single saveall function,
i got this table,
CREATE TABLE IF NOT EXISTS `dates` (
`date` varchar(10) COLLATE utf8_unicode_ci NOT NULL
)
what i'm trying to do is let user select start date and end date using JQuery calander, once submit all the dates between this range will be saved into database, i already got the array of dates eg:
`array(
(int) 0 => '5/8/2013',
(int) 1 => '6/8/2013',
(int) 2 => '7/8/2013',
(int) 3 => '8/8/2013',
)
`
then my controller looks like this:
public function index(){
if ($this->request->is('post')) {
$this->Date->create();
$data = array();
$data['dates']=array();
$startDate = $this->request->data['Date']['from'];
$endDate = $this->request->data['Date']['to'];
$datesBlocked = $this->loopDates($this->request->data['Date']['from'],$this->request->data['Date']['to']);
$data['dates'][] = $this->request->data['Blockdate']['from'];
$data['dates'][] = $this->request->data['Blockdate']['to'];
/*foreach($datesBlocked as $data) {
$data['dates'][] = $data;
}*/
if($this->Date->saveAll($data)) {
$this->Session->setFlash(__('done'));
if ($this->Session->read('UserAuth.User.user_group_id') == 1) {
// $this->redirect("/manages");
}
}
}
public function loopDates($from,$to){
$blockdates = array();
$start = strtotime($from);
$end = strtotime($to);
debug($start);
$counter = 0;
for($t=$start;$t<=$end;$t+=86400) {
$d = getdate($t);
$blockdates[$counter++] = $d['mday'].'/'.$d['mon'].'/'.$d['year'];
}
debug($blockdates);
return $blockdates;
}
issue was i can't get foreach work, if i uncomment the foreach, i got error said Illegal string offset 'dates' , so i commented that and try to only add the start date and end date to the array to see if that works, then i got another error said.
`array(
'dates' => array(
(int) 0 => '08/05/2013',
(int) 1 => '09/05/2013'
)
)
`
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1005]Code
cuz i'm trying to insert 2 values into one field...i know it should be sth like
`array(
'dates' => array( (int) 0 => '08/05/2013',
)
'dates' => array((int) 1 => '09/05/2013'
))
`but can't figure out how to do it. Any help would be much appreciate!!!!
The structure you'll want your array to save multiple dates using saveAll() is this:
array(
'Date' => array(
0 => array(
'date' => '08/05/2013',
),
1 => array(
'date' => '09/05/2013',
)
),
)
I know that this is a little late, but to write multiple rows in a loop, you have to proceed the save with a create().
eg:
foreach($items as $lineItem){
$this->Invoice->create();
$this->Invoice->save(array(
'user_id'=>$property['User']['id'],
'invoice_id'=>$invId['Invoices']['id'],
'item_id'=>$lineItem['item_number'],
'quantity'=>$lineItem['quantity'],
'price'=>$lineItem['mc_gross']
);
}
Just thought it was worth mentioning, hopefully it will help someone.
I have the foll code as:
$table_project_win = new Application_Model_DbTable_AfterWinProject();
$data_win = array(
'project_id' => $project_id,
'project_name' => $project,
'project_type_id' => $pro_type,
'start_date' => $dateStart,
'end_date' => $dateEnd,
'project_size' => $size,
'project_description' => $pro_des
);
$table_project_win->insert($data_win);
Here I get the $dateStart and $dateEnd variabled using as:
$dateStartt = $this->_getParam('dateStart');
echo 'date Start: '.$dateStartt;
$dateStart='"'.$dateStartt.'"';
$dateEndd = $this->_getParam('dateEnd');
$dateEnd='"'.$dateEndd.'"'
By using getParam I get the value of the date that the user has given input But when i will insert it into the database I use as
$dateStart='"'.$dateStartt.'"';
$dateEnd='"'.$dateEndd.'"'
But in the database table the value for date inserted is '0000-00-00' While when I echo the $dateStart which I have got through getParam It gives the correct value as '2012-12-11'.What is the reason of it??What Should I do??
replace $dateStart='"'.$dateStartt.'"';
with
$dateStart= $dateStartt ;
or
$dateStart='`'.$dateStartt.'`';