I'm trying to perform a query in Laravel 7 that gets the month part of a date field. I tried the following queries
$test = MyModal::selectRaw('month("date_col") as temp')->get();
$test = MyModal::select(DB::Raw('month("date_col") as temp'))->get();
$test = DB::table('my_table')->select('month("date_col") as temp')->get();
All variation of the same query. If I dump the query log, the query is correct for all 3
select month("date_col") as temp from "my_table"
If I run this on my DB I get the result as well. But I keep getting this error in laravel:
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such function: month (SQL: select month("date_col") as temp from "my_table")
Am I doing something wrong? And is there a way to do this query in laravel?
Edit: Sorry forgot to mention this is with Laravel's unit testing
I think the problem in the way you use Month function
you don't set quotations for the column name, it should be:
$test = MyModal::selectRaw('month(date_col) as temp')->get();
it should work
You can do something like this:
MyModal::select(DB::raw("MONTH(date_col) month"))->get();
Thanks to OMR's comment this solution finally worked
$test = MyModel::selectRaw('strftime("%m", "date_col") as temp')->get();
Update: It looks like what I had in the beginning worked fine and the unit test was the only part throwing this error. Since I was working with mysql while the test environment was using sqlite which apparently doesnt like the "month()" function which OMR did point out in his comment. So this solution works in the test but not in live. Couldn't figure out how to change the test environment to use in memory mysql instead of sqlite. If anyone knows how to please add an answer here.
Related
I'm trying to run this: $query->selectRaw('count(?)', [$column]) on Laravel 7.0, but gives me an error:
SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR: could not determine data type of parameter $1.
PS: $column is a string.
When I put count(distinct ?), it results in wrong count.
I already tried "{$column}" and '%'.$column.'%', but it didn't work.
I tried other ways for hours, until I ask in a community and someone answered me that it's not possible to do this. The binding will only works with column values or something like that, despite that it doesn't have detailed uses of the selectRaw method.
Well, I've lost many hours, so I gave up and went to my objective with another approach.
You can use param in selectRaw by using quotes
Example:
$column = 1;
$query->selectRaw('count(**$column**)');
I want to load data from a SQLite database in PHP using Atlas.Orm.
When I run the following snippet, I get a set of 1773 results, but each result is the same!
$atlas = Atlas::new('sqlite:[Path To Database]');
$result = $atlas->select(Stop::class)->fetchRecords();
Can anyone tell me whats wrong here?
After several hours of desperation, I found the issue by myself. The ORM needs the PRIMARY_KEY constant in the corresponding *Table class to be set, otherwise fetching records will fail like this.
I am using the Laravel query builder for fetching some data from a sqlsrv database. The table I am looking for is dbo.[Reukema Blocq Maneschijn BV$Time Slot (Weighbridge)]. Not my choice. The database is developed by an other company.
I keep getting a General error: 20018 Invalid object name error when executing my query. I double checked the name for typos but I couldn't find one.
What I did find was a problem in compiling the query. This is my code to test the problem:
$query = $connection->query()
->from('Reukema Blocq Maneschijn BV$Time Slot (Weighbridge)')
->toSql()
When I dump the $query, I get the following:
string(67) "select * from [Reukema Blocq Maneschijn BV$Time Slot ](Weighbridge)"
The ] is in the wrong place here.
This problem keeps existing, even when I'm using the raw() helper:
$query = $connection->query()
->from($connection->raw('dbo.[Reukema Blocq Maneschijn BV$Time Slot (Weighbridge)]'))
->toSql()
Even in this last example, the ] moves from the end of the string, to just before the (.
Why is this? Am I missing an important rule/mechanic for compiling sqlsrv queries?
The following code does work. That makes it extra weird for me:
$connection->select('select [Time Slot] as [id] from [Reukema Blocq Maneschijn BV$Time Slot (Weighbridge)]');
So I think there is something wrong in the SqlServerGrammar#compileFrom method. Why does Laravel compile it like this?
Personally, I would highly recommend changing the object's name; that is an awful choice. If you can't do this, perhaps create a synonym that is far more "usable". For Example:
CREATE SYNONYM dbo.WeighbridgeSlot FOR dbo.[Reukema Blocq Maneschijn BV$Time Slot (Weighbridge)];
Then in your application code call the synonym instead:
$query = $connection->query()
->from('WeighbridgeSlot')
->toSql()
After doing some tests with xDebug. I found the issue. It's the Illuminate\Database\Query\Grammars\SqlServerGrammer#wrapTableValuedFunction method.
Laravel mistakenly sees my table name as a table valued function. That's why the compilation of the query isn't working correctly.
The fix I used for now is a little bit dirty:
$query = $connection->query()
->from('Reukema Blocq Maneschijn BV$Time Slot (Weighbridge) as time_slots')
->toSql()
By adding a alias to the end of my from method, the table name get's compiled in an other way. This prevents the table valued function compilation.
I'm not sure if I should report this as a bug. Or if the table name I have to work with simply is invalid.
Edit: I reported the bug and created a fix. You can find the issue (and PR) here
Why this query is not working. Executing same thing in sql database returns me this one result that's in image. so doing q select * from kolejka where data like '2017-04-08%' in mysql works. In php artisan tinker it won't work and I cannot figure out why.
When you're using all() first, you get all data and then work with it. like won't work here. So, do this instead:
\App\Kolejka::where('data', 'like', '2017-04-08%')->get();
If you just want to get records by date, just use whereDate():
\App\Kolejka::whereDate('data', Carbon\Carbon::parse('2017-04-08'))->get();
this query works fine using the php_mssql driver:
INSERT INTO Table(columnName) VALUES ('text');
SELECT SCOPE_IDENTITY() AS id;
Table does have an id column, which is an identity.
I would execute that query, and get the last id in the table.
The same code doesn´t work if the query is executed using Microsoft´s php_sqlsrv driver.
I don´t get any error when executing the query (sqlsrv_query function) , but i get the following error when calling sqlsrv_fetch_array:
"The active result for the query contains no fields"
I´ve googled a lot, and didn´t find no answer, it was a big surprise for me that no one faced this problem before, it seems like nobody is using this driver, even though is the "official" one since PHP 5.3 release...
Thanks.
In the initial CTP the field indices started at 1. Later they were changed to start at 0.
Try something like this:
// connection to the dbserver
$result = sqlsrv_query("INSERT INTO Table(columnName) VALUES ('text'); SELECT SCOPE_IDENTITY() AS ID");
echo "The last insert_id is".lastId($result);
function lastId($queryID) {
sqlsrv_next_result($queryID);
sqlsrv_fetch($queryID);
return sqlsrv_get_field($queryID, 0);
}