Symfony 2 join not working doctrine and MySQL

心不动则不痛 提交于 2019-12-25 12:17:28

问题


Note: this post was solved using this method, the problem was in one of my entities, so any thing I tried that would in normal conditions work, was bad functioning because of that. I do not know how to mark it now.

I have the following repository entities: Vehicle, Job, FuelPurchase.

For intance vahicle:

/**
 * @ORM\Entity
 * @ORM\Table(name="vehicle")
 * @ORM\Entity(repositoryClass="TeamERP\TransportBundle\Entity\VehicleRepository")
 */
class Vehicle
{
 /**
 * @ORM\Column(type="integer", name="id_vehicle")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $idVehicle;
/**
 * @ORM\Column(type="string", length=7, name="plate_number")
 */
protected $plateNumber;

/**
 * @ORM\Column(type="integer", name="distance_to_service")
 */ 
protected $DistanceToServiceKm;
/**
 * @ORM\Column(type="integer", name="last_service_odo")
 */ 
protected $lastServiceODOKm; 
/**
 * @ORM\Column(type="string", length=100, name="make")
 */
protected $makeName;   
/**
 * @ORM\Column(type="string", length=100, name="model")
 */
protected $modelName;

/**
* @ORM\OneToMany(targetEntity="Job", mappedBy="vehicles")
*/
protected $jobs;

/**
* @ORM\OneToMany(targetEntity="FuelPurchase", mappedBy="vehicles")
*/
protected $fuelPurchaces;

public function __construct()
{
    $this->jobs = new ArrayCollection();
    $this->fuelPurchaces = new ArrayCollection();
}
 ...  

and Fuel puchase is this:

/**
 * @ORM\Entity
 * @ORM\Table(name="fuel_purchace")
 * @ORM\Entity(repositoryClass="TeamERP\TransportBundle\Entity\FuelPurchaseRepository")
 */

class FuelPurchase
{
/**
 * @ORM\Column(type="integer", name="id_fuel_purchace")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $idFuelPurchace;
/**
 * @ORM\Column(type="string", length=20, name="invoice_number")
 */
protected $invoice; 
/**
 * @ORM\Column(type="datetime", name="date_time")
 */
protected $dateTime;
/**
 * @ORM\Column(type="float", name="fuel_used", nullable=true) 
 */
protected $fuelUsed;
/**
 * @ORM\Column(type="float", name="fuel_price", nullable=true) 
 */
protected $fuelPrice;
/**
 * @ORM\Column(type="float", name="km_odo", nullable=true)
 */    
protected $kmOdo;    
/**
* @ORM\ManyToOne(targetEntity="Vehicle", inversedBy="FuelPurchace")
* @ORM\JoinColumn(name="id_vehicle", referencedColumnName="id_vehicle")
*/
protected $vehicles;
/**
* @ORM\Column(type="string", length=250, name="refuling_remarks", nullable=true)
*/
protected $remarks;
/**
* @ORM\Column(type="string", length=100, name="refuling_person", nullable=true)
*/
protected $refueler;
...

Also the Job:

class Job
{
/**
 * @ORM\Column(type="integer", name="id_job")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $idJob;
/**
 * @ORM\Column(type="string", length=20, name="delivery_number")
 */
protected $deliveryNo; 
/**
 * @ORM\Column(type="datetime", name="date_time")
 */
protected $dateTime;
/**
 * @ORM\Column(type="string", length=200, name="destination")
 */
protected $destination;      
/**
 * @ORM\Column(type="float", name="km_odo_start", nullable=true)
 */    
protected $kmOdoStart;   
/**
 * @ORM\Column(type="float", name="km_odo_end", nullable=true)
 */    
protected $kmOdoEnd;      

/**
 * @ORM\Column(type="float", name="fuel_used", nullable=true) 
 */
protected $fuelUsedLitre;
/**
 * @ORM\Column(type="float", name="fuel_price", nullable=true) 
 */
protected $fuelPrice;    
/**
 * @ORM\Column(type="string", length=100, name="driver_name", nullable=true)
 */    
protected $driverName;
/**
 * @ORM\Column(type="string", length=250, name="crew_names", nullable=true)
 */    
protected $crewNames;
/**
 * @ORM\Column(type="string", length=7, name="triler_plate_number", nullable=true)
 */
protected $trilerPlateNumber;
/**
 * @ORM\Column(type="string", length=500, name="remarks", nullable=true)
 */
protected $remarks;
/**
 * @ORM\Column(type="string", length=500, name="return_load_plan", nullable=true)
 */
protected $returnLoadPlan;
/**
* @ORM\ManyToOne(targetEntity="Vehicle", inversedBy="job")
* @ORM\JoinColumn(name="id_vehicle", referencedColumnName="id_vehicle")
*/
protected $Vehicles;    

/**
* @ORM\ManyToOne(targetEntity="JobStatus", inversedBy="job")
* @ORM\JoinColumn(name="id_job_status", referencedColumnName="id_job_status")
*/
protected $jobStatus;

/**
* @ORM\ManyToOne(targetEntity="JobType", inversedBy="job")
* @ORM\JoinColumn(name="id_job_type", referencedColumnName="id_job_type")
*/
protected $jobType;

/* My functions Distance calculator*/
public function getJobDistance ()
{
    return $this->kmOdoEnd - $this->kmOdoStart;
}
....

I am trying to make joins between the 3 of them to make a report, but I have started simple; a join between Vehicle and FuelPurchase, but I cant make it work. Check out my Vehicle repository:

class VehicleRepository extends EntityRepository
{
public function findByCriteria ($dateStart, $dateEnd)
{
    $query = $this->createQueryBuilder();
            $query->select('v', 'f')
            ->from('TeamERPTransportBundle:Vehicle', 'v')
            ->innerJoin('TeamERPTransportBundle:FuelPurchase', 'f')
            ->groupBy('v.plateNumber')
        ->getQuery();
    return $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
}
}

I am getting this error:

ContextErrorException: Warning: Missing argument 1 for Doctrine\ORM\EntityRepository::createQueryBuilder(), called in D:\Web\wamp\www\team\src\TeamERP\TransportBundle\Entity\VehicleRepository.php on line 17 and defined in D:\Web\wamp\www\team\vendor\doctrine\orm\lib\Doctrine\ORM\EntityRepository.php line 81

Edition 1: I have also tryed this:

    $query = $this->createQueryBuilder('v');
            $query->select('v', 'f')
            ->from('TeamERPTransportBundle:Vehicle', 'v')
            ->innerJoin('TeamERPTransportBundle:FuelPurchase', 'f')
            ->groupBy('v.plateNumber');
        $aux = $query->getQuery();
     $result = $aux->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);   
     return $result;

And the error that I receive is this:

[Syntax Error] line 0, col 106: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got ','

Ramoving from:

    $query = $this->createQueryBuilder('v');
            $query->select('v', 'f')
            ->innerJoin('TeamERPTransportBundle:FuelPurchase', 'f')
            ->groupBy('v.plateNumber');
        $aux = $query->getQuery();
     $result = $aux->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);   
     return $result;

It gives this error:

[Syntax Error] line 0, col 113: Error: Expected Literal, got 'BY'

Edition 2: I managed to make a join with 2 tables work using the following code:

class VehicleRepository extends EntityRepository
{
public function findByCriteria ($dateStart = null, $dateEnd=null)
{
    $query = $this->createQueryBuilder('v')
            ->select('v.plateNumber','SUM(f.fuelUsed) as totalFuel', 'SUM(f.fuelUsed*f.fuelPrice) as totalFuelCost')
            ->join('v.fuelPurchaces', 'f')
            //->join('v.jobs', 'j')
            ->groupBy('v.plateNumber')
            ->getQuery()->getResult();
    return $query;
}
}

Now what I cant do is to add a third table, if I remove the comment mark from the join for jobs, then I receive the following error: ContextErrorException: Notice: Undefined index: vehicles in D:\Web\wamp\www\team\vendor\doctrine\orm\lib\Doctrine\ORM\Query\SqlWalker.php line 887

Any Idea? Thank you any help will be appreciated.


回答1:


Change

$query = $this->createQueryBuilder();

to

$query = $this->createQueryBuilder('v');

[Edit]:

BTW - I think you don't need from part:

->from('TeamERPTransportBundle:Vehicle', 'v')

because you allready creating query inside Vehicle repository




回答2:


This is how you write the query correctly using DQL.

$this->getDoctrine()->getManager()
                ->createQueryBuilder()
                ->select($alias)
                ->from($table, $alias);

And when joining you can straight call the table name BUT with the alias of the joining table at the beginning. In this case, I assume 'fuel_purchase' is your table.

So, the corrected query will be,

$query = $this->getDoctrine()->getManager()
            ->createQueryBuilder()
            ->select('v', 'f')
            ->from('TeamERPTransportBundle:Vehicle', 'v')
            ->innerJoin('v.fuel_purchase', 'f')
            ->groupBy('v.plateNumber')
            ->getQuery();

return $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

Hope this helps. Cheers!




回答3:


should $vehicles in FuelPurchace Entity be inversed by $fuelPurchaces and not FuelPurchace?



来源:https://stackoverflow.com/questions/23288988/symfony-2-join-not-working-doctrine-and-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!