Faker YML add 1 hour to a date - faker

My question is about Faker.
I need to add one hour to a created date
Like this :
MyEntity:
startAt: '<dateTimeBetween("- 10 days", "now")>'
endAt: $startAt + 1 hour
Thx for your help.

Well that does not exist yet. Need to create a custom provider
Like this :
public static function manipulateTime($date, $action = '-30 years')
{
$date = new \DateTime($date->format('Y-m-d H:i:s'));
$date->modify($action);
return $date;
}

Related

symfony 3.4 Doctrine COUNT

this code works well to count how many "2014-01-01 00:00:00" there is in my column "session" but I want the day to be anything not only 01.
class BooknowRepository extends \Doctrine\ORM\EntityRepository
{
public function findAllOrderedByNb() {
return $this->createQueryBuilder('a')
->select('COUNT(a)')
->where('a.session = :session')
->setParameter('session', '2014-01-01 00:00:00')
->getQuery()
->getSingleScalarResult();
}
}
class BooknowRepository extends \Doctrine\ORM\EntityRepository
{
public function findAllOrderedByNb() {
return $this->createQueryBuilder('a')
->select('COUNT(a)')
->where('a.session LIKE :session')
->setParameter('session', '%2014-01%')
->getQuery()
->getSingleScalarResult()
;
}
}
Several dates
but I want the day to be anything not only 01
If I have understood you correctly, your want find count of dates from array. In SQL this is implemented using WHERE IN syntax — in Doctrine you are greatly encouraged to use $qb->expr()->in() method.
$sessions = ['2014-01-01 00:00:00', '2014-01-03 00:00:00'];
...
$qb = $this->createQueryBuilder('a');
...
$qb->select('COUNT(a)')
->where($qb->expr()->in('a.session', ':sessions'))
->setParameter('sessions', sessions)
Dotrine doc: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#high-level-api-methods
Date range
If you want to get count of rows in month/year you need set a interval until the start of the next month
->andWhere('a.session >= :startSession')
->andWhere('a.session < :finishSession')
->setParameter('startSession', '2014-01-01 00:00:00')
->setParameter('finishSession', '2014-02-01 00:00:00')

Get Magento 2 collection based on final_price

I have the following code to get a Magento 2 product collection:
<?php namespace Qxs\Related\Block;
class Related extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
\Magento\Catalog\Model\Product\Visibility $productVisibility,
\Magento\Framework\Registry $registry,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
$this->productStatus = $productStatus;
$this->productVisibility = $productVisibility;
$this->_registry = $registry;
parent::__construct($context, $data);
}
public function getProductCollection()
{
try {
$product = $this->_registry->registry('current_product');
$range_percentage = 35;
$price_temp = round($product->getFinalPrice() / 100 * $range_percentage);
$price_from = $product->getFinalPrice() - $price_temp;
$price_to = $product->getFinalPrice() + $price_temp;
$categories = $product->getCategoryIds();
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addCategoriesFilter(['in' => $categories])
->addPriceDataFieldFilter('%s >= %s', ['min_price', $price_from])
->addPriceDataFieldFilter('%s <= %s', ['min_price', $price_to])
->addMinimalPrice()
->addAttributeToFilter('entity_id', ['neq' => $product->getId()])
->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
->setVisibility($this->productVisibility->getVisibleInSiteIds())
->setPageSize(5);
return $collection;
} catch (\Exception $e) {
var_dump($e->getMessage());
}
}
}
Code above is updated with a working example
It will return a result with addtofieldfilter 'price' but it does not work with final_price attribute. I need to sort based on final_price because configurable products don't have a price. The code returns: invalid attribute name.
How can I filter on price range in final_price attribute?
Thanks,
The final_price is part of the price index tables, so you can't work with it the same way as you would do with fields and attributes. You need to join in the price index to be able to filter and sort based on final_price. Luckily, Magento has added a few nifty functions for us to use on the product collection; addPriceDataFieldFilter() and addFinalPrice().
Solution
To be able to achieve the logic you describe above, you would want to change your code to something like this:
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addCategoriesFilter(['in' => $categories])
->addPriceDataFieldFilter('%s >= %s', ['final_price', $price_from])
->addPriceDataFieldFilter('%s <= %s', ['final_price', $price_to])
->addFinalPrice()
->addAttributeToFilter('entity_id', ['neq' => $product->getId()])
->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
->setVisibility($this->productVisibility->getVisibleInSiteIds())
->setPageSize(5);
Note the order of the functions. You must always call addFinalPrice() after all of the addPriceDataFieldFilter() or else the filter won't be applied.
Bonus
If you want to sort by final_price, you can add following code after addFinalPrice():
$collection->getSelect()->order('price_index.final_price ASC');
References
https://github.com/magento/magento2/blob/2.2.9/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php#L1465
https://github.com/magento/magento2/blob/2.2.9/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php#L2265

Difference between startDate and endDate-Symfony

Can someone assist me with this, I have a student table and I want to ensure that the user enters a date range from now to 3 months. I tried this but it didn't give me the results I wanted. Thinking about using datediff but not sure where I would put it. Is there another way like using a custom validation to validate the date.
* #Assert\Range
* (
* min= "today", max="+3 months"
* )
Error message:
This value should be a valid number.
#Assert\Callback(methods={"validatePayrollPeriod"})
public function validatePayrollPeriod(ExecutionContextInterface $context) {
$days = $this->startdate->diff($this->enddate)->days;
if ($days <= 7 || $days > 14) {
$context->buildViolation('Not a valid payroll period.')
->atPath('enddate')
->addViolation();
}
}
You could try to make a validation in your setter.
Something like
public function setEndDate($endDate)
{
if(your end date - your start date < 3){
$this->endDate= $endDate;
}else{
Throw whatever exepection you cant
}
return $this;
}

Symfony Solarium bundle datetime range

$client = $this->solr->getClient();
$query = $client->createSelect();
$facetSet = $query->getFacetSet();
$facetSet->createFacetField('id')->setField('publication_year');
$facet = $facetSet->createFacetRange('yearsranges');
$facet->setField('publication_year');
$facet->setStart( --MIN DATE VALUE-- );
$facet->setGap( --I NEED TO MAKE RANGE OF 10 YEARS-- );
$facet->setEnd( --NOW DATE TIME-- );
$solrQuery = '*:*';
$query->setQuery($solrQuery);
$query->setRows(0);
$data = $client->select($query)->getFacetSet()->getFacet('yearsranges');
dump($data);
die;
Let first ask you, if it is valid to make ranges of dates in solr facets
"publication_year" field in solr collection. This date is actually a string in this format.
"2009-10-29T23:00:00Z"
Yes it's valid or just use a query filter:
$createQuery->createFilterQuery('range')->setQuery('createdate:[1995-12-31T23:59:59.999Z TO 2007-03-06T00:00:00Z]');
For a facet:
$facet->createQuery('createdate:[1995-12-31T23:59:59.999Z TO 2007-03-06T00:00:00Z]');

Symfony3 Doctrine findByDate filter by month and/or year

I need to query Statistics by month and/or year but I get this error:
Error: Expected known function, got 'YEAR'
My code:
public function findByMonthYear($month, $year)
{
$qb = $this->createQueryBuilder('p')
->where('YEAR(p.date) = :year')
->andWhere('MONTH(p.date) = :month');
$qb->setParameter('year', $year)
->setParameter('month', $month);
return $qb->getQuery()->getOneOrNullResult();
}
With some research it shows that dql doesn't have YEAR() function so it's fare...http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/working-with-datetime.html
In the end, I'm not stick on the solution. So if you've got a clean one for the same result I'll take it as an answer.
A colleague told me that a solution as the following one may works:
where('p.date = :date')
setParameter('date', ''.$year.'-'.$month.'-%') // 2016-07-%
No success so far.
public function findByMonthYear($month, $year)
{
$fromTime = new \DateTime($year . '-' . $month . '-01');
$toTime = new \DateTime($fromTime->format('Y-m-d') . ' first day of next month');
$qb = $this->createQueryBuilder('p')
->where('p.date >= :fromTime')
->andWhere('p.date < :toTime');
->setParameter('fromTime', $fromTime)
->setParameter('toTime', $toTime);
return $qb->getQuery()->getOneOrNullResult();
}

Resources