I have a table in which the values are recorded along with the date.
My date field is of string type:
"1401/09/23"
I want to get rows that date back to yesterday:
public async Task<List<Reservation>> GetReservations()
{
return await _context.Reservations.OrderByDescending(r => r.DateReserve).ToListAsync();
}
I also used the following code, but it gives an error!
return await _context.Reservations.Where(r => DateTime.Parse(r.DateReserve, CultureInfo.InvariantCulture) >= DateTime.Parse(DateConvertor.ToShamsi(), CultureInfo.InvariantCulture)).ToListAsync();
Error :
Assuming your code is correct functionally (I have no idea what a "Shamsi" is), you can fix your error by using ".AsEnumerable()":
return _context.Reservations.AsEnumerable().Where(r => DateTime.Parse(r.DateReserve, CultureInfo.InvariantCulture) >= DateTime.Parse(DateConvertor.ToShamsi(), CultureInfo.InvariantCulture)).ToList();
Please note that this means that your complete table will be pulled into memory of your PC and the statement will be executed by C# code on your PC, instead of a database statement on your database.
Related
I am trying to create a Filter that will that will return the rows where at least one minute has passed from the stored transactionDate. I am not getting an error but it is not returning any rows. The transactionDate is a timestamp in MongoDB and is stored as "transactionDate" : ISODate("2016-09-30T20:29:19.448Z")
Thanks! \m/ \m/
var filter = Builders<MyDocument>.Filter.Eq("Genre", "Rock");
filter = filter & (Builders<MyDocument>.Filter.Lt(x => x.transactionDate, DateTime.Now.AddSeconds(Math.Abs(60) * (-1))));
using (var cursor = await MyCollection.Find(filter)
.Sort(Builders<MyDocument>.Sort.Ascending(x => x.artist).Ascending(x => x.rating)).ToCursorAsync())
{
// foreach...
}
The above code actually does work. I had an issue in the data causing no results to be returned. \m/ \m/
I'm making my first laravel project, using postgres, and I'd like to be able to access all the people with a birthday this month (my people table has a birthdate field that's a date). I can use extract to get these records from the database, like so:
select * from people
where extract (month from birthdate) = 11;
But when I try a few different ways in my controller I get 'unknown column' errors:
$birthday_people = DB::table('people')
->where ("extract(month from birthdate)", "=", "11")
->get();
(I'll ultimately adjust it to compare with Carbon::now()->month, and use the model Person::all(), but until I get some results coming through I'm going as simple as possible)
Is there a special way to get the month from a date in laravel?
Update: I'm using a scope now in my Person model. I can get person results to come through when I give it an exact date:
public function scopeBirthdays($query)
{
return $query->where('birthdate', '=', '1947-11-02');
}
And I can get results back for month if I do it this way, but the catch is it doesn't seem to know it's a collection of People anymore (I can't access person columns when I display it out and I can't chain other scopes):
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', ['11'])->get();
}
Laravel's query builder offers 'whereMonth'- (seems the most right), but it gave me an 'undefined function' error until I put the bool on the end, and now the current error suggests that it's interpretting number of months instead of which one(?):
public function scopeBirthdays($query)
{
return $query->whereMonth('birthdate', '=', Carbon::today()->month, true);
}
I get:
Syntax error: 7 ERROR: syntax error at or near "month"
LINE 1: select * from "people" where 1 month("birthdate") = $1
^ (SQL: select * from "people" where 1 month("birthdate") = 11)
Final update: I was able to get results back (that were correctly interpretted as people) by using whereRaw in my scope:
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', [Carbon::today()->month])->orderBy ('birthdate', 'asc');
}
Thanks, everyone!
based on previous question try:
$birthday_people = DB::table('people')
->whereRaw("extract(month from birthdate)", "=", "11")
->get();
You can set is as relationship
public function custom(){
return $this->hasMany('App\Models\People')->whereRaw("extract(month from birthdate)", "=", "11");
}
You could try something like this. It will return as an instance of App\People so you will be able to use your eloquent functions still.
public function scopeBirthdays($query)
{
return $query->where('birthdate', 'LIKE', Carbon::today()->year . '-'.Carbon::today()->month.'%');
}
I don't have much experience with Carbon, I'm assuming that Carbon::today() will return an object with the year, month, and date.
I have an entity query that when I run increments the value of my field. I am using entity framework and sql server 2012. Here is my query;
public void GetLastAccountNumber(ProductLine productLine, Action completed)
{
EntityQuery query = WASMDomainContext.GetContactCustomerAccountsQuery()
.Where(cca => cca.ProductLineId == productLine.Id)
.OrderBy(cca => cca.AccountNumber);
WASMDomainContext.Load(query, loadOp =>
{
Exception error = null;
ContactCustomerAccount lastAccount = null;
if (loadOp.HasError)
error = loadOp.Error;
else
lastAccount = loadOp.Entities.LastOrDefault();
// Invoke completion callback
completed(lastAccount, error);
}, null);
}
Query should return the last account number which is an integer field for now. However it returns an incremented value. For example in my table I have an accountnumber 0 the query returns an entity with account number as 1. My account number field is not auto increament and I find this very strange. And each time the above is called the AccountNumber field value increases by one but the database value will remain 0. I just want the query to return what is in my database. Any idea why this could be happening? Any help will be appreciated. Thank you all.
I'm trying to create a query that pulls information about sellers from my database, but only if their store has launched in the last 3 days. The easiest way I can think of to calculate the date for the query is using a new DateTime() object. When I output my code to test it, it's in the proper string for MySQL to query it with, but whenever I try to bind the variable, I get an error. I'm using Zend_Db to query, (PDO adapter)
action:
public function indexAction()
{
$dateMod = new DateTime();
$dateMod->modify('-2 days');
$dateMod->format('Y-m-d H:i:s');
// get sellers initialized in last 3 days
$sellerTable = new Application_Model_DbTable_Sellers();
$select = $sellerTable->select()->setIntegrityCheck(false);
$select->from(array('s' => 'seller'),array('sellerID', 'businessName'));
// select firstName, lastName, picture from user table, and businessName and sellerID from seller table.
$select->join(array('u' => 'user'), 's.userID = u.userID', array('firstName', 'lastName', 'picture'));
$select->where('s.active = 1 AND s.contentApproval = 1 AND s.paymentApproval = 1 AND s.featured = 1');
$select->where('s.launchDate > ?', $dateMod);
$select->order('s.launchDate DESC');
$newSellers = $sellerTable->fetchAll($select);
When I assign $dateMod to the view, it outputs the correct Y-m-d H:i:s format. But when I plug it into the query, I get the following error:
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 ') ORDER BY `b`.`launchDate` DESC' at line 2
If I hardcode a value into dateMod in the mysql timestamp format, the query works fine. How can I access just the string value of the timestamp in the DateTime object? getTimestamp returns a unix formatted timestamp, even after assigning a format.
The format() function returns the formatted date, so you need to assign that to a variable for use in the query:
$dateFormatted = $dateMod->format('Y-m-d H:i:s');
$select->where('s.launchDate > ?', $dateFormatted);
I have not clearly issue during query using two criterials like Id and Other. I use a Repository storing some data like id,iso,value. I have created an index("_id","Iso") to performs queries but queries are only returning my cursor if i use only one criterial like _id, but is returning nothing if a use two (_id, Iso) (commented code).
Are the index affecting the response or the query method are failing?
use :v1.6.5 and C# official.
Sample.
//Getting Data
public List<BsonObject> Get_object(string ID, string Iso)
{
using (var helper = BsonHelper.Create())
{
//helper.Db.Repository.EnsureIndex("_Id","Iso");
var query = Query.EQ("_Id", ID);
//if (!String.IsNullOrEmpty(Iso))
// query = Query.And(query, Query.EQ("Iso", Iso));
var cursor = helper.Db.Repository.FindAs<BsonObject>(query);
return cursor.ToList();
}
}
Data:
{
"_id": "2345019",
"Iso": "UK",
"Data": "Some data"
}
After that I have Updated my data using Update.Set() methods. I can see the changed data using MongoView. The new data are correct but the query is always returning the sames olds values. To see these values i use a page that can eventually cached, but if add a timestamp at end are not changing anything, page is always returning the same olds data. Your comments are welcome, thanks.
I do not recall offhand how the C# driver creates indexes, but the shell command for creating an index is like this:
db.things.ensureIndex({j:1});
Notice the '1' which is like saying 'true'.
In your code, you have:
helper.Db.Repository.EnsureIndex("_Id","Iso");
Perhaps it should be:
helper.Db.Repository.EnsureIndex("_Id", 1);
helper.Db.Repository.EnsureIndex("Iso", 1);
It could also be related to the fact that you are creating indexes on "_Id" and the actual id field is called "_id" ... MongoDB is case sensitive.
Have a quick look through the index documentation: http://www.mongodb.org/display/DOCS/Indexes