Hello i'm working in project with Symfony 2.4 i want to make a select using QueryBuilder but i have a exception :
FatalErrorException: Error: Call to undefined method getEntityManager()
This is my code :
$session=$this->get('session');
$id_client=$session->get('client');
$emConfig = $this->getEntityManager()->getConfiguration();
$emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
$qb = $this->createQueryBuilder('f');
$qb->select('SUM(f.montantTtc)');
$qb->from('factureBundle:Facture', 'f');
$qb->where('f.client = :id_client');
$qb->groupBy('YEAR(f.dateEdition)');
$qb->setParameter('id_client', $id_client);
$factures_by_years=$qb->getQuery()->getResult();
plz help me
here is the topic :
https://simukti.net/blog/2012/04/05/how-to-select-year-month-day-in-doctrine2.html
and this is the code :
<?php
// .........
// Doctrine2 repository class for entity 'Post'
// .........
public function findOneByYearMonthDay($year, $month, $day)
{
$emConfig = $this->getEntityManager()->getConfiguration();
$emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
$emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
$emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');
$qb = $this->createQueryBuilder('p');
$qb->select('p')
->where('YEAR(p.postDate) = :year')
->andWhere('MONTH(p.postDate) = :month')
->andWhere('DAY(p.postDate) = :day');
$qb->setParameter('year', $year)
->setParameter('month', $month)
->setParameter('day', $day);
$post = $qb->getQuery()->getSingleResult();
return $post;
}
Related
I'm working on symfony, and i have a doctrine problem :
class Utilisateur implements UserInterface, PasswordAuthenticatedUserInterface
{ /**
* #ORM\OneToMany(targetEntity=UserGestionnaire::class, mappedBy="user", cascade={"persist"})
*/
private $userGestionnaires;
class UserGestionnaire
{
/**
* #ORM\ManyToOne(targetEntity=Societe::class, inversedBy="userGestionnaires")
*/
private $gestionnaire;
So here i have a One To Many Relation,and i want to Know how Many user don t have the the usergestionnaire gestionnaire id 1002
I tried a lot of testing and searching, but i didn t found any solution,
Here what i got so far :
public function countUserNoIdSpecificGest()
{
$limitDate = date_format(new \DateTime("now - 2 years"), 'Y-m-d');
$query = $this->createQueryBuilder('u');
$queryB = $query
->select('count(distinct(u.id))')
->join('u.mouvements', 'm')
->join('u.userGestionnaires', 'ug')
->join('ug.gestionnaire', 'sg')
// Here : ->andWhere('sg.id NEVER BE 1002')
->join('m.rules', 'r')
->join('r.avenantModule', 'am')
->join('am.module', 'mod')
->join('mod.manager', 's')
->andWhere('s.id = 1002')
->andWhere('u.deletedAt IS NULL')
->andWhere('m.deletedAt IS NULL')
->andWhere(
$query->expr()->orX(
$query->expr()->orX(
$query->expr()->gte('m.dateOut', ':limitDate'),
)
)
)
->setParameter('limitDate', $limitDate)
->getQuery()
->getSingleScalarResult();
return $queryB;
}
To be more understandable, here is the part of the PHP code that I would like to transfer to WHERE doctrine :
$usersNotVerified = $this->em->getRepository(Utilisateur::class)->getUserNoIdSpecificGest();
$users = array();
foreach ($usersNotVerified as $userNotVerified) {
$gestionnaires = $userNotVerified->getUserGestionnaires();
$finded = false;
foreach ($gestionnaires as $gestionnaire) {
$societyId = $gestionnaire->getGestionnaire()->getId();
if ($societyId == 1002) {
$finded = true;
}
}
if (!$finded) {
array_push($users, $userNotVerified);
}
}
$countNoId = count($users);
public function getUserNoIdSpecificGest()
{
$limitDate = date_format(new \DateTime("now - 2 years"), 'Y-m-d');
$query = $this->createQueryBuilder('u');
$queryB = $query
->join('u.mouvements', 'm')
->join('m.rules', 'r')
->join('r.avenantModule', 'am')
->join('am.module', 'mod')
->join('mod.manager', 's')
->andWhere('s.id = 1002')
->andWhere('u.deletedAt IS NULL')
->andWhere('m.deletedAt IS NULL')
->andWhere(
$query->expr()->orX(
$query->expr()->orX(
$query->expr()->gte('m.dateOut', ':limitDate'),
)
)
)
->setParameter('limitDate', $limitDate)
->addOrderBy('u.id', 'asc')
->getQuery()
->getResult();
return $queryB;
}
I'm working on a Symfony project that makes use of a
Repository file in which I have declared and created an instance of a query builder
(repository1)
$mk = $this->createQueryBuilder('up');
$later = date("Y-m-d", strtotime("-3 months"));
$today = date("Y-m-d");
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
automatically this generates data for my page between the above dates.
Now I want to create a form where I can make a search between two dates.
with the intention of passing the posted data from this form to my controller into my method below
My controller below (controller1)
protected function getData(EntityManagerInterface $entityManager,Request $request) {
// this code to get data from repository
$entityManager->getRepository(repository1::class)->getName()
// receive posted data
$date1 = $request->get('date');
$date2 = $request->get('date');
// now how to pass data to my repository1
}
Please how do I edit what I have to post data from within my controller to my (repository1)
so then it would be
$mk = $this->createQueryBuilder('up');
$later = $date1;
$today = $date2;
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
is this even possible, or im over thinking it?
RepositoryClass
public function getByStartEndDate(DateTimeInterface $start, DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}
Controller Class
private function getData(Request $request, RepositoryClass $repo)
{
// May need to convert these to DateTime objects
$start = $request->get('start');
$end = $request->get('end');
$records = $repo->getByStartEndDate($start, $end);
// do what you want with the records here
}
You can give the dates as parameters to your method.
Controller Class:
protected function getData(EntityManagerInterface $entityManager,Request $request) {
$start = $request->get('start') ? new \DateTime($request->get('start')) : null;
$end = $request->get('end') ? new \DateTime($request->get('end')) : null;
$result = $entityManager->getRepository(Entity::class)->getName($start, $end);
// do with result as desired
}
Repository Class:
public function getName(\DateTimeInterface $start, \DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}
I have a problem with Doctrine woring in my Symfony project.
That's my code:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\Common\Persistence\ObjectManager;
use Factory\MainBundle\Entity\Lastauction;
use Factory\MainBundle\Entity\Offers;
class AuctionListController extends Controller
{
private $em;
private $qb;
private $offer;
public function getAuctionListAction()
{
$this->em = $this->getDoctrine()->getEntityManager();
$this->qb = $this->em->createQueryBuilder();
getAllAccount();
for($offset=0; $offset<20000; $offset++)
{
$this->insertOffers();
}
return new Response('Offers list generated');
}
private function getAllAccount()
{
$this->qb->select('ac.mail')
->from('FactoryMainBundle:Account', 'ac');
$result = $this->qb->getQuery()->getResult();
$this->accounts = array_column($result, 'mail');
}
private function insertOffers()
{
foreach($this->offers as $id => $offer)
{
if($this->checkIfExsistOffer($offer))
{
echo $offer .'<br>';
$offerObj = new Offers();
$offerObj->setOffer($offer);
$offerObj->setPage(2);
$this->em = $this->getDoctrine()->getManager();
$this->em->persist($offerObj);
if (($id % $this->batchSize) == 0)
{
$this->em->flush();
$this->em->clear();
}
}
}
$this->em->flush();
$this->em->clear();
$this->offers = array();
}
private function checkIfExsistOffer($offerUrl)
{
$this->qb->select('o.id')
->from('FactoryMainBundle:Offers', 'o')
->where("o.offer=:offer")
->setParameter('offer', $offerUrl);
$result = $this->qb->getQuery()->getResult();
return (isset($result['0']['id'])) ? 1 : 0;
}
}
And I get this error:
[Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.
[2/2] QueryException: [Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.
[1/2] QueryException: SELECT o.id FROM FactoryMainBundle:Account ac, FactoryMainBundle:Lastauction la, FactoryMainBundle:Offers o, FactoryMainBundle:Offers o WHERE o.offer='123'
Why Doctrine takes tables from other queries?
$this->qb->select('o.id')
->from('FactoryMainBundle:Offers', 'o')
->where("o.offer=:offer")
->setParameter('offer', $offerUrl);
$result = $this->qb->getQuery()->getResult();
Breakdown of your codeflow regarding $this->qb:
1) In getAuctionListAction: $this->qb = $this->em->createQueryBuilder();
2) In getAllAccount:
$this->qb->select('ac.mail')
->from('FactoryMainBundle:Account', 'ac');
3) In checkIfExsistOffer (through insertOffers), 20.000x due to your loop in getAuctionListAction:
$this->qb->select('o.id')
->from('FactoryMainBundle:Offers', 'o')
->where("o.offer=:offer")
->setParameter('offer', $offerUrl);
Long Story short: You're adding multiple tables to your $this->qb querybuilder object (through $this->qb->from(...)), that's why they all get queried.
private function checkIfExsistOffer($offerUrl)
{
$res = $this->getDoctrine()->getRepository('FactoryMainBundle:Offers')
->createQueryBuilder('o')
->select('o.id')
->where("o.id=:offer")
->setParameter('offer', 1)
->getQuery()
->getSingleResult(); //return single result
var_dump($res);die; //test
}
Hey i am novice in CI so please forgive! I am trying to join 2 tables in codeigniter and i am getting here these error in my code
Call to undefined method CI_DB_mysql_driver::row_array() in
C:\xampp\htdocs\Hostel\application\models\payfees.php on line 16.
My Code for the method is here like these
public function payu($id,$month){
$where = "where generatebills.student_id='".$id."' and generatebills.month='".$month."'";
$query = $this->db->select('*')
->from('generatebills')
->join('student','student.student_id=generatebills.student_id')
->where($where);
return $query->row_array();
}
Don't forget the missing ->get() method. Plus, remove the WHERE in the string:
$where = "name='Joe' AND status='boss' OR status='active'";
http://www.codeigniter.com/userguide2/database/active_record.html
I'd suggest use an array instead:
public function payu($id,$month)
{
// $where = "generatebills.student_id='".$id."' and generatebills.month='".$month."'";
$where = array(
'generatebills.student_id' => $id,
'generatebills.month' => $month,
);
$query = $this->db->select('generatebills.*')
->from('generatebills')
->join('student','student.student_id = generatebills.student_id')
->where($where);
return $query->get()->row_array();
// ^
}
I'm not sure if it's that I'm not doing correctly but this is giving me an error:
I have 2 Entities: Task and TaskUser. They are connected by a onetoMany.
What I want to do is this:
foreach($tasks as $task){
echo $task->getTitle;
echo $task->getTaskUser()->getFirstName();
}
This is my query in the Task Repository:
public function findTasksByUsers($user = false)
{
if($user){
$qb = $this->_em->createQueryBuilder();
$qb
->select('t', 'tu')
->from('\Entities\Task', 't')
->leftJoin('\Entities\TaskUser', 'tu', \Doctrine\ORM\Query\Expr\Join::WITH, 't.id = tu.task')
->where('tu = :user')
->setParameter('user', $user)
->orderBy('t.createDate', 'DESC');
return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT);
}
}
When I do this loop:
$tasks = $this->em->getRepository('\Entities\Task')->findTasksByUsers($user);
foreach($tasks as $task){
echo $task->getTitle();
}
I get the the title of the first task, and then an error like this:
Title of first task
Fatal error: Call to undefined method Entities\TaskUser::getTitle() in D:\sites\db\application\controllers\TasksController.php on line 35
Any idea why this is happening? Thanks!
$qb->select('t', 'tu')
the issue is here as you're selecting both entities.
If you want only Task entity modify your DQL as follows
$qb->select('t')
However, to me, you could only procede that way (in your controller; if you aren't into controller, use DI to access entity manager)
//retrieve all TaskUser object
$em = $this->getDoctrine()->getManager();
$tu_repo = $em->getRepository('YourBundleName:TaskUser');
$tu_array_collection = $tu_repo->findBy(array('user'=>$user));
foreach ($tu_array_collection as $tu) {
$first_name = $tu->getFirstName();
foreach ($tu->getTasks() as $task) {
echo $first_name;
echo $task->getTitle();
}
}
of course you may need to adapt your code with right findBy array, and with correct methods from TaskUser entity