I want to update all row that has no 'timemodified' based on another column from the same query.
DB::table('sco_tracks')->where('timemodified', '')->update([
'timemodified' => Carbon::createFromFormat('Y-m-d H:i:s' , DB::raw('updated_at'))->timestamp
]);
With this code I get: Data missing {"exception":"[object] (InvalidArgumentException(code: 0): A four digit year could not be found
the raw query would be
UPDATE sco_tracks t SET timemodified=UNIX_TIMESTAMP(created_at) WHERE timemodified IS NULL;
the code for laravel:
DB::table("sco_tracks")->where('timemodified','')->update(['timemodified'=>DB::raw('UNIX_TIMESTAMP(updated_at)')]);
and if the value of timemodified field is null you can use this code:
DB::table("sco_tracks")->whereNull('timemodified')->update(['timemodified'=>DB::raw('UNIX_TIMESTAMP(updated_at)')]);
Related
Possible duplicates:
Laravel: How to order date, change the date format and group by the date?
Laravel Carbon format wrong date
I created a line chart using chartjs, the chart and data fetching is working fine. However the order of the dates is wrong. It starts off with Aug 2022 instead of Jan 2022.
When I use the orderBy(), it shows orderBy() doesn't exists error.
When I use createFromFormat() of Carbon, it shows missing data error.
Why? I parsed the date with Carbon and the column type is datetime, shouldn't it be working?
This is my laravel collection:
$data = TrafficViolation::select('id', 'violationDateTime')
->get()
->sortBy('violationDateTime')
->groupBy(function($data) {
return Carbon::parse($data['violationDateTime'])->format('M, Y');
});
The orderBy() is a Query Builder method. Once you call get(), you get a Collection instance.
To order the records in your DB you need to call orderBy() first, and than get():
UPDATE:
I have included the records count, and date format. You still need to order the records by the violationDateTime column
$data = User::selectRaw('COUNT(*) as violation_count, DATE_FORMAT(violationDateTime, \'%M, %Y\') as formatedDate')
->groupBy('formatedDate')
->orderBy('violationDateTime')
->get();
if your get a Syntax error or access violation: 1055 you need to change the stritc mode in mysql to false in /config/database.php change ['connections' => ['mysql' => ['strict' => false]]]
I have a table with JSON column which can be empty, or if it is not empty it is possible not to have the key. I am trying following query for updates:
Award::where('background->logo', 'name')
->update(['background->logo' => null]);
I am getting following error:
SQLSTATE[22032]: <<Unknown error>>: 3141 Invalid JSON text in argument 1 to function json_extract: \"The document is empty.\" at position 0. (SQL: update `awards` set `background` = json_set(`background`, '$.\"logo\"', ?), `awards`.`updated_at` = 2022-04-11 11:13:53 where json_unquote(json_extract(`background`, '$.\"logo\"')) = 4ppcNtOGsTzzkNlv.png and `awards`.`deleted_at` is null)"
Background column can be null, and the logo key can be absent.
What I am doing wrong? Is it possible to update JSON columns like this?
I try to check if a column from a relationship table is null, . But with my current code I get an error.
The column is "best_match" in the second whereNotNull.
SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry
for table "questions"↵LINE 1:
$questions = Model::whereNotNull('question_id');
if($excepted_questions){
$questions->whereNotIn('id', $excepted_questions);
}
$questions->where('votes', '!=' , $confidence_specs->votes)
->orWhere('weight', '!=' , $confidence_specs->weight)
->with('questions')
->inRandomOrder();
//HERE I try to check if that column is null or not
if($confidence_specs->best_match){ // this can be true / false ,if is true I check if that column is null
$questions->whereNotNull('questions.best_match');
}
$questions->limit($nr_of_questions)
->get();
You will have to use whereHas to use where statement with the relationship model or you must have joined the table.
Otherwise just using where statement won't work on multiple tables.
For more information check the docs Querying Relationship Existence
So your query should have been
if($confidence_specs->best_match) {
$questions->whereHas('questions', function($query) {
$query->whereNotNull('best_match');
});
}
with will just eager loads the model it doesn't let you perform MySQL query on it.
i am getting data using crawl and trying to insert into database. i get abbreviations of company name and have a command to get the full form of the abbreviations. it works fine if the company name already exists in companies table, and when the command handle is run new company name is also inserted and i can get the name from the table but cannot insert the name as it shows error. here is the code:
$data['symbol']=$es[1];
$name=DB::table('companies')
->select('stock_name')
->where('stock_symbol',$data['symbol']=$es[1])
->first();
if(!empty($name->stock_name)){
$data['company_name']= $name->stock_name;
}else{
\Artisan::call("company:handle");
$name=DB::table('companies')
->select('stock_name')
->where('stock_symbol',$data['symbol']=$es[1])
->first();
$data['company_name']= $name->stock_name;
}
You can resolve it by doing
//...
$data['company_name']= $name->stock_name ?? '';
//...
Null coalescing (??) is a new operator introduced in PHP 7. This
operator returns its first operand if it is set and not NULL.
Otherwise it will return its second operand.
I'm using JTable to store a record in a table. My table has 3 primary keys(pid,eid,sid). I want to store (Insert,update) a record
my code:
$row =& JTable::getInstance('mytable', 'Table');
$row->load(
array(
'pid' =>$pid,
'eid' =>$eid,
'sid' =>$sid
)
);
$row->data = $data;
if (!$row->store()) {
JError::raiseError(500, $row->getError() );
}
The load function runs with warning:
Warning: mysql_real_escape_string() expects parameter 1 to be string, object given in ...\joomla\database\database\mysql.php on line 193
and the store function raise an error:
, but the store raise an error with the SQL statement. The SQL statement contains the field names and new values and 'WHERE' keyword but without a condition.
any help?
The load function takes an integer as an input (see here http://docs.joomla.org/JTable/load) so you cannot pass it an array. The integer you pass it should be the primary key of your table. Here you can use any one of your 3 primary keys, because being primary it will be unique.