Hi I'm trying to give amount of days and get records between that day and now.
$now = new \DateTime();
$days = 14;
$to = $now->sub(new \DateInterval('P'.$days.'D'));
$qb = $this->createQueryBuilder('c')
$qb->andWhere('c.createdDate BETWEEN :from AND :to')
->setParameter('from', $now)
->setParameter('to', $to);
$qb->getQuery()->getResult();
in my db created_date column and have a record which contain 2018-12-12. But unfortunately query returns no value :(. It would be great help if someone can solve. And I'm using sub to get minus date.
Valid query is:
$from = new \DateTime('-14 days');
$to = (new \DateTime())->setTime(23, 59, 59);
$qb = $this->createQueryBuilder('c')
$qb->andWhere('c.createdDate BETWEEN :from AND :to')
->setParameter('from', $from)
->setParameter('to', $to);
$result = $qb->getQuery()->getResult();
The reason it didn't work for you, is because the \DateTime is a mutable type. By changing a copy, you also changed the previous date object:
$from = new \DateTime();
// below you mutate the $from object, then return its instance
$to = $from->sub(new \DateInterval('P10D'));
// effect is both $from and $to reference the same object in memory
var_dump(spl_object_hash($from) === spl_object_hash($to));
echo $from->format('Y-m-d') , '<br>';
echo $to->format('Y-m-d');
Will result in:
bool(true)
2018-12-07
2018-12-07
You mapped the property createdDate as datetime in Doctrine. Personally I always use the datetime_immutable type. Instead of DateTime I get to work with DateTimeImmutable, which, compared to DateTime is immutable by design so I don't have to worry about any references:
$from = new \DateTimeImmutable();
$to = $from->sub(new \DateInterval('P10D'));
var_dump(spl_object_hash($from) === spl_object_hash($to));
echo $from->format('Y-m-d') , '<br>';
echo $to->format('Y-m-d');
Results in:
bool(false)
2018-12-17
2018-12-07
Related
I m trying to filter my document on created_at with whereMonth/whereYear clauses. But it always returns empty collection. I can't understand why.
Example :
$collection = MyModel::whereMonth('created_at', '06')->get();
I tried to change type of parameter with '6' or (int) 6... but nothing changed.
Someone to explain me why it doesn't work as documentation says (jenssegers package or laravel).
I didn't found any solution...
Thank you.
Ok i found solution. I made my query in a whereRaw and used this :
$month = (int) $request->month;
$queryMonth = [
'$expr' => [
'$eq' => [['$month' => '$created_at'], $month],
]];
$collection = Model::whereRaw($queryMonth)->get();
Same for requesting "year".
Thanks for all.
$collection = MyModel::all();
foreach($collection as $result)
{
$datetime = $result->created_at;
$date = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $datetime);
$month = $date->month;
if($month == '06')
{
$collection = MyModel::whereMonth('created_at', $month)->get();
}
}
I'm trying to create a sort function where if it's selected it will display the necessary amount of orders. For example if the user selects to display orders from the last 3 months then that needs to be displayed.
The problem I'm having is that nothing is being shown when I dd($three_months)
public function trackOrders()
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$orders = Auth::user()->orders->sortByDesc('order_date');
$orders->transform(function($order, $key){
$order->cart = unserialize($order->cart);
return $order;
});
$from = Carbon::now('+2:00');
$to = $from->copy()->subMonth(3);
$three_months = Order::whereBetween('created_at', [$from, $to])->get();
dd($three_months);
return view('public.users.track-orders', compact('menus_child', 'contacts', 'orders', 'order_item'));
}
but when I do dd($three_months) nothing shows up. I only get
Collection {#320 ▼
#items: []
}
Order matters when using SQL's BETWEEN. Your $from value is greater than your $to value. So try swapping them around:
$to = Carbon::now('+2:00');
$from = $from->copy()->subMonth(3);
$three_months = Order::whereBetween('created_at', [$from, $to])->get();
Maybe it's because you are not Formatting DateTime
$from = Carbon::now('+2:00')->format('Y-m-d H:i:s');
$to = $from->copy()->subMonth(3)->format('Y-m-d H:i:s');
Try This code.
Edit: You cant Use copy() method on string. so you can do.
$to = Carbon::now('+2:00')->subMonth(3)->format('Y-m-d H:i:s');
I am getting cinema title + times using API from Cinelist, I then want to save these values into a database.
At the moment, it does save but only 1 record, the last one. However, I want it to save each one.
Also each time it is run I want to update existing records instead of creating new ones unless there are more results.
So usually there are 5 records, each time I run the function I want to update the database with the new 5 records, however, if it's a different day and there are 6 records I want to update 5 records and insert 1 extra one so there is 6.
My code so far:
function odeon(){
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565');
$data = json_decode($data);
foreach($data->listings as $listing){
$title = $listing->title;
$time = implode(', ', $listing->times);
$id = + 1;
$films = Film::where('id', $id)->first();
if (!$films) {
$films = new Film();
}
$films->title = $title;
$films->times = $time;
$films->save();
}
}
You may use eloquent's updateOrCreate method to insert non-existent data and update existing data.
function odeon(){
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565');
$data = json_decode($data);
foreach($data->listings as $listing){
$title = $listing->title;
$time = implode(', ', $listing->times);
Films::updateOrCreate([
'title' => $title,
'$times' => $time
]);
}
}
I get two date from user for example :
2016-10-01
2016-11-05
now I would like to get all dates between these two dates :
2016-10-01
2016-10-02
2016-10-03
2016-10-04
...
2016-11-05
I think I must use the carbon library. but I don't know how can I do !
Try this:
$from = Carbon::parse('2016-10-01');
$to = Carbon::parse('2016-11-05');
With Carbon
$dates = [];
for($d = $from; $d->lte($to); $d->addDay()) {
$dates[] = $d->format('Y-m-d');
}
return $dates;
How to use:
JFactory::getDbo()->insertObject('#__card_bonus', $object);
with on duplicate key update ?
You have a few options:
1) Check for an entity id. This is my preferred option, because it only uses a single query, is reusable for any object, and is database agnostic - meaning it will work on whichever DBMS you choose, whereas the other two options are exclusive to MySQL.
if (isset($object->id)) {
$db->updateObject('#__card_bonus', $object);
}
else {
$db->insertObject('#__card_bonus', $object, 'id');
}
I often create an abstract model with a save(stdClass $object) method that does this check so I don't have to duplicate it.
2) Write your own query using the MySQL ON DUPLICATE KEY UPDATE syntax, which is a proprietary extension to the SQL standard, that you have demonstrated understanding of.
3) Write your own query using MySQL's proprietary REPLACE INTO extension.
<?php
$jarticle = new stdClass();
$jarticle->id = 1544;
$jarticle->title = 'New article';
$jarticle->alias = JFilterOutput::stringURLSafe($jarticle->title);
$jarticle->introtext = '<p>re</p>';
$jarticle->state = 1;
$jarticle->catid = 13;
$jarticle->created_by = 111;
$jarticle->access = 1;
$jarticle->language = '*';
$db = JFactory::getDbo();
try {
$query = $db->getQuery(true);
$result = JFactory::getDbo()->insertObject('#__content', $jarticle);
}
catch (Exception $e){
$result = JFactory::getDbo()->updateObject('#__content', $jarticle, 'id');
}
I use this method - are not fully satisfied, but ...
or for not object method:
$query = $db->getQuery(true);
$columns = array('username', 'password');
$values = array($db->quote($username), $db->quote($password));
$query
->insert($db->quoteName('#__db_name'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$query .= ' ON DUPLICATE KEY UPDATE ' . $db->quoteName('password') . ' = ' . $db->quote($password);
$db->setQuery($query);
JFactory::getDbo()->insertObject('#__card_bonus', $object, $keyName);
The name of the primary key. If provided the object property is updated.
Joomla doc ...