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)')]);
In my project current_profile is a JSON object column for EmployeePromotionAndShifting model. I want to update a key named division_i of current_profile column.
The JSON object is like this:
"current_profile" =>
{"staff_id":"2927","division_id":"84","department_id":"200","unit_id":null}
I am getting an error:
"This database engine does not support JSON operations." at
vendor\yajra\laravel-oci8\src\Oci8\Query\Grammars\OracleGrammar.php:1
Code to update in database!
EmployeePromotionAndShifting::where('staff_id',$currentProfile['staff_id'])->update(['current_profile->division_id' => 555,]);
I want to update division_id key of current_profile column for a particular row.
i have tried this to get records matching value 1 in products_applicable column
Coupon::whereJsonContains('products_applicable',['1'])->get();
how do we get records using dynamic value like $value instead of ['1'], i have tried this
Coupon::whereJsonContains('products_applicable',[$value])->get();
and
Coupon::whereJsonContains('products_applicable',$value)->get();
Nothing Worked>>>> How do i get all records matching $value in products_applicable column which is json datatype
also I want to merge this 2 codes like i want all records having null value at products_applicable and having $value
$data= Coupon::whereNull('products_applicable')->get();
Coupon::whereJsonContains('products_applicable',$value)->get();
. hope anyone can help me..
You can achieve it by passing an array to whereJsonContins()method.
For example:
$value = [1, 2, 3];
$data= Coupon::whereNull('products_applicable')
->orWhereJsonContains('products_applicable', $value)->get();
Notice: You can pass whereJsonContains() method both an array or a value (string or integer).
Why I have got 3 values when I attach "dresscodes"?
$event->dresscode()->attach($request->get('dressCodesValue'));
this is error message
SQLSTATE[01000]: Warning: 1265 Data truncated for column 'dress_codes_id' at row 1 (SQL: insert into `dress_codes_events` (`dress_codes_id`, `events_id`) values (1,2, 28))
Here is a relation of Events table
public function dresscode()
{
return $this->belongsToMany(DressCodes::class);
}
Here are dresscode value when print out from controller $request->get('dressCodesValue') // 1,2
I fixed it.
Here is my problem
When I pass my data into FormData() and post it via axios.post It's converts my array value into string
Solution
just explode string back to array and pass that value into attach() method
I'm new to Laravel and trying to do a string query in Eloquent. I was trying to use DB::statement, but I kept getting errors about placeholders in the query string. It seems I either don't have the syntax right, or bindings are unimplemented or unsupported?
The reason I want to use statement is because I'm doing an INSERT... SELECT, which I haven't been able to find any documentation about in Eloquent.
Here's my code:
$ php artisan tinker
Psy Shell v0.5.2 (PHP 5.6.13-0+deb8u1 — cli) by Justin Hileman
>>> echo \DB::statement('CREATE DATABASE :db', [':db'=>'test']);
Illuminate\Database\QueryException with message 'SQLSTATE[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 '?' at line 1 (SQL: CREATE DATABASE :db)'
>>> \DB::statement('CREATE DATABASE ?', ['test']);
Illuminate\Database\QueryException with message 'SQLSTATE[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 '?' at line 1 (SQL: CREATE DATABASE test)'
These are the two syntax forms (? and :string) from PDO. Other methods in DB such as select and insert support this, according to the documentation.
The relevant parts of these errors are near '?' at line 1 (SQL: CREATE DATABASE :db) and near '?' at line 1 (SQL: CREATE DATABASE test). MySQL thinks there is an unbound ? in the query string. I didn't even use that syntax in the first query. I'm concluding from that that the bind() method did not correctly bind my placeholders.
This question on Laracasts is asking about the syntax, but there is no accepted answer.
Edit One answer says that statement() doesn't support CREATE. I tried some queries out with SELECT, and got the same results, with both placeholders:
>>> \DB::statement('SELECT 1 WHERE \'a\' = ?', array('a'));
Illuminate\Database\QueryException with message 'SQLSTATE[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 'WHERE 'a' = ?' at line 1 (SQL: SELECT 1 WHERE 'a' = a)'
>>> \DB::statement('SELECT 1 WHERE \'a\' = :letter', array(':letter'=>'a'));
Illuminate\Database\QueryException with message 'SQLSTATE[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 'WHERE 'a' = ?' at line 1 (SQL: SELECT 1 WHERE 'a' = :letter)'
Actually, you can use create and drop query in DB::statement(), but named bindings is not used in that way.
Here are some queries that will success.
drop and create do not accept bindings.
>>> \Db::statement('create database test')
=> true
>>> \Db::statement('drop database test')
=> true
Do not use backslash and single quotes in the statement
>>> \Db::statement('insert into users (id, name) values (?, ?)', ['1', 'John'])
=> true
DB::statement() only return ture when success, so if you want to see select results, you should use DB::select()
>>> \Db::statement('select * from users')
=> true
>>> \Db::select('select * from users')
=> [
{#770
+"id": 1,
+"name": "John",
},
]
Remove leading : in the second argument.
>>> \Db::statement('update users set name = :name where id = :id', ['id' => 1, 'name' => 'John'])
=> true
You will get affect rows if you use DB::update and DB::delete
>>> \Db::delete('delete from users where id = :id', ['id' => 1])
=> 1
The errors you receive are only indirectly related with Laravels DB::statement() function. They all fail within that method at the line
return $me->getPdo()->prepare($query)->execute($bindings);
within the file vendor/laravel/framework/src/Illuminate/Database/Connection.php
Responsible for that failure is the resulting call to PDO::prepare()
The Docuemenation says:
Parameter markers can represent a complete data literal only. Neither part of literal, nor keyword, nor identifier, nor whatever arbitrary query part can be bound using parameters. For example, you cannot bind multiple values to a single parameter in the IN() clause of an SQL statement.
Also have a look at the user contributed notes at the above php.net documentation. Additionally have a look at Can PHP PDO Statements accept the table or column name as parameter?
Your create examples are not supported by PDO.
The reason your SELECT examples fail is simply due to an invalid syntax.
\DB::statement('SELECT 1 WHERE \'a\' = ?', array('a'))
You are simply missing the FROM clause. This example works perfeclty well at my test computer:
$ret = \DB::statement('SELECT 1 FROM `users` WHERE `username` = ?', ["gregor"]);
But
$ret = \DB::statement('SELECT 1 WHERE `username` = ?', ["testname"]);
Generates the exact error, you receive.
Also note, that \DB::statement does not return any ressources. It just indicates by returning true or false, whether the query suceeded.
Your option is to use DB::raw() within your insert() statement, if you want to use INSERT...SELECT. Some googling will help you, to find the proper solution. Maybe as Starting Points: Raw Queries in Laravel, or How to use raw queries in Laravel
What you're trying to do is passing the table name through binding.
DB::statement('select * from ?',['users'])
which according to this post, it's not possible.
of course if you want to sanitize the data you can use an array of short codes like so:
$tables = ['users','test','another'];
and the query would look something like:
$code = 0;
DB::statement("select * from $tables[$code] where a=?",[2]);
DB::statement("create table $tables[$code]");