Query a date range with DMZ DataMapper and CodeIgniter - codeigniter

I cannot find the solution in the docs for this simple problem.
I want to fetched a set of objects from the database in a specific date range.
I'm using DMZ Datamapper in the CodeIgniter environment.
$items = new Entity();
$items->where('date_created', 'date1 < x < date2');
$items->get();
Maybe one needs to use the $items->where_in_func(...) method?

Answer is simple:
$items->where('date_created >', '2011-02-26 14:00:13');
$items->where('date_created <', '2011-02-26 16:00:13');

Related

Best approcah for getting the object in the foreach loop in laravel using eloquent?

I have some properties and i want to get the object for each property, currently, I am using the eloquent in the foreach loop like this as shown in the image that will describe the best..
but it is really not a good approach because if I have 100 published property I will making 100 calls to the DB... and that is not correct?
I need a suggestion and a proper solution to this query?
Thanks in advance
Before foreach you can get all the RentalProperty items from db like this:
$allRentalProperties = RentalProperty::all();
and in foreach loop you can get those items without connecting database like this:
$propertyObj = $allRenatalProperties -> where('id', $property['id']) -> first();
Also, you can use array shorthand.
$newArray = [];
it's much simple and readable.
You can do array pluck before loop:
$propertyIds = Arr::pluck($published_properties, 'id');
Then you can make a whereIn query to get only those data which are in $published_properties object
$propertyObj = RentalProperty::whereIn('id', $propertyIds);
Then you can access that object with id if you change array key with record id.

date calculation in laravel model

I want to return values in my model based on dates but not sure how to?
Logic
calculate the date that post has published + 7 days after that and return true or false.
example
Let say I want add new label in posts from the date that post published till 7 days after that, and in the day 8th that new label be removed.
How do I do that?
Update
I ended up with something like this in my model currently
public function isNew($query){
return $query->where('created_at', '<=', Carbon::now()->toDateTimeString());
}
but it returns Undefined variable: isNew in my blade.
please give me your suggestions.
Are labels stored in a separate table from your posts? You could use 'effective dating'. Have indexed 'show_at' and 'hide_at' fields in your labels table. Have entries there get created as soon as the post does. You could use database triggers to do this, or model observers. And when querying for all labels related to a given post, make sure they're between those dates (or those dates are null).
For a more simple solution, you could do a whereRaw('CURRENT_DATE <= DATE_ADD(dateFieldName, INTERVAL 7 DAY)'). If timezones are a factor, you could use the CONVERT_TZ() function, though it's generally good practice to store everything in UTC to avoid those issues.
I would recommend you make use of Carbon:
https://carbon.nesbot.com/docs/#api-difference
That link should help a lot but to point you in the correct direction, you should be able to do a comparison:
I assume you DB date is held in ISO (Y-M-D, eg: 2019-01-07)
$date= Carbon::createFromFormat('Y-m-d', $dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
Code for Add Label here
}
Or if you are using timestamps:
$date= Carbon::createFromTimestamp($dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
Code for Add Label here
}
Solved
thanks for all the helps I solved my issue with code below:
public function getisNewAttribute(){
$now = Carbon::now();
return Carbon::parse($now) <= Carbon::parse($this->created_at)->addDays(7);
}

how to select one month back records from data base in laravel

how select one month back records from current date from database in laravel. I am trying this code.
This is controller code.
class LoginHistoryController extends Controller {
public function index()
{
$login_history = LoginHistory::where('login_date','BETWEEN', '(CURDATE() -
INTERVAL 10 DAY) AND CURDATE()' )->get();
}
}
but i am getting error.
I will have a approach something like this. First I will calculate the date like
$today = date('Y-m-d');
$date = date_create($today);
date_sub($date, date_interval_create_from_date_string("30 days"));
$beforeOneMonth = date_format($date, "Y-m-d");
You should have the intended value in $beforeOneMonth by now. Now you can compare it in anyway you like whether you use IN operator or >=. For eg.
$login_history = LoginHistory::where('login_date','>=', $beforeOneMonth)->get();
Give it a try. If you are storing date in some other format, you can do your own tricks to format the date and do the thing
Another way to do it would be with whereRaw:
$login_history = LoginHistory::whereRaw(
'login_date BETWEEN (CURDATE() - INTERVAL 10 DAY) AND CURDATE()'
)->get();
Note that whereRaw has the side effect of making your code less portable since you're using SQL that might be specific to your database server. But sometimes you just can't do what you would like using the query builder.

Chaining queries in Play! Framework

is there a way to chain queries in the "Play!" framework instead of manually writing a query ?
Something like:
Model m = Model.where("name","Bill").where("gender","m").first();
I wonder because I recently switched from Codeigniter + dmz to grails then now to "Play!" and have been a bit disappointed by the queries chaining compared to the framework mentioned above
PS: I'm obviously not talking about the fetch() and the from() methods.
There is a JpqlSelect object with wich you can do
public static Model findBill() {
JpqlSelect select = new JpqlSelect().from("Model").where("name=?").param("Bill").andWhere("gender=?").param("m");
return find(select.toString(), select.getParams().toArray()).first();
}
This helper is far from being complete but it may suits your needs
You can do it with java.persistence Criteria API like that:
CriteriaQuery q = JPA.em().getCriteriaBuilder().createQuery(Model.class)
q.where(<Expression>).where(<Expression>);
TypedQuery<Model> tq = JPA.em().createQuery(q);
List<Model> result = tq.getResultList();
Look here and here for start
An other option could be using http://www.querydsl.com/ with it's jpa integration.

Django-nonrel sorting by foreignkey

Is there a way of returning items from a database in django-nonrel, using 'order_by' on a foreignkey?
Full details are as follows:
#Models.py
class Post(models.Model):
article = models.TextField(help_text='Paste or type HTML in here')
pub_date = models.DateField()
....
class TagItems(models.Model):
title = models.CharField(max_length=200)
....
class TagRel(models.Model):
the_post = models.ForeignKey('Post')
the_tag = models.ForeignKey('Tag')
TagRel defines a ManytoMany relationship between Post and TagItems classes.
I am wanting to get a list of articles for each tag.
#Desire output
My tag
-my first post
-my second post
My second tag
- my other post
- another post
All is good so far, as I use the following to filter the data:
def tagged_posts():
tag_items = TagItems.objects.all()
li =[]
for item in tag_items:
tag_rel_item = TagRel.objects.filter(the_tag__pk = item.pk)
li.append(tag_rel_item)
return {'list_of_objects': li}
I am using db-indexer to define the filter part of the query in db-indexes.py. All this works fine but I want to order my posts by publication dates.
Django docs tell me to use:
TagRel.objects.filter(the_tag__pk = item.pk).order_by('the_tag__pub_date')
But the order_by('the_tag__pub_date') part does not appear to be supported by django-nonrel.
The following also works in normal Django:
TagRel.objects.filter(the_tag__pk = item.pk).order_by('the_post')
This works because the Posts are already sorted by date in the model.
But this also does not appear to work in django-nonrel.
So my question is how do I return my posts ordered by date (latest>oldest)?
Thanks in advance
I'm taking a guess at this - you're using a ManyToManyField. I believe that's implemented using a ListProperty on App Engine's datastore.
See the section in the datastore documentation labeled "Properties With Multiple Values Can Have Surprising Behaviors":
http://code.google.com/appengine/docs/python/datastore/queries.html
That's most likely why your results appear unsorted. ManyToMany relations aren't supported natively in GAE. You'd probably have to sort them yourself after you get the results back.

Resources