Ожидаемое значение типа Entity для поля ассоциации получило Entity1 вместо этого при использовании ResolveTargetEntityListener

Я использую ResolveTargetEntityListener из Doctrine для доступа к таблицам SQL, которые находятся во внешней базе данных.

Когда я использую createQueryBuilder для запроса данных по внешнему / базовому классу Vehicle, я получаю следующую ошибку:

Expected value of type "AppBundle\Entity\VehicleFox" for association field "AppBundle\Entity\FM_Positions#$truck", got "FoxBundle\Entity\Vehicle" instead.

Когда я делаю это во внутреннем классе VehicleFox, Query возвращает NULL.

Есть ли что-то, что я пропустил?

Ниже приведен контроллер, с которым я делаю запрос с помощью соответствующих функций. Я также включил используемые классы и интерфейсы, а также файл config.yml.

FmController

<?php

namespace BWT\FMBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Request;
use Vendors\FM;
use AppBundle\Entity\FuelData;
use MaxBundle\Entity\UdoDriver;
use FoxBundle\Entity\Vehicle;
use AppBundle\Entity\FM_Positions;

class FMController extends Controller
{
public function latestPositionsAction(Request $request)
{
$_render_args = array();
$_results = array();
$tripProcesses = new FM();
$success = $this->login($tripProcesses);

If ($success === true) {
$_results = $tripProcesses->getTrackingData();
}
if ($_results) {
$_render_args['results'] = $_results;
}
$this->CreateFmPositions($_results);
return $this->render('Telematics/latestPositions.html.twig', $_render_args);
}

private function CreateFmPositions(array $results)
{
foreach ($results as $result){

$resultArray = (array) $result;
$vehicle = $this->getVehicleFM($resultArray['VehicleID']);
$position = new FM_Positions();
if ($vehicle) {
$position->setTruck($vehicle[0]);
}
$em = $this->getDoctrine()->getManager();
$em->persist($position);
$em->flush();
}
}

private function getVehicleFM(int $vehFmId)
{
$repository = $this->getDoctrine()->getRepository('FoxBundle:Vehicle', 'foxem'); // error for incorrect Entity
//$repository = $this->getDoctrine()->getRepository('AppBundle:VehicleFox'); // returns NULL
$query = $repository->createQueryBuilder('v')
->where('v.fmId = :fmid')
->setParameter('fmid', $vehFmId)
->getQuery()
->getResult();

return $query;
}
}

Fm_Positions.php

<?php
// src/AppBundle/Entity/FM_Possitions.php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use AppBundle\Model\VehicleInterface;
use AppBundle\Model\UDODriverInterface;

/**
* @ORM\Entity
* @ORM\Table(name="fm_positions")
* @author sarah
*
*/

class FM_Positions
{
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Model\VehicleInterface", inversedBy="fm_positions")
* @ORM\JoinColumn(name="truck_id", referencedColumnName="id")
* @var VehicleInterface
*/
private $truck;
// ...
}

Базовый класс автомобиля

<?php
namespace FoxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Vehicle
* @ORM\Table(name="vehicle", uniqueConstraints={@ORM\UniqueConstraint(name="fleet_number", columns={"fleet_number"})}, indexes={@ORM\Index(name="log_book_date", columns={"log_book_date"})})
* @ORM\Entity
*/
class Vehicle
{
/**
* @var string|null
* @ORM\Column(name="fleet_number", type="string", length=20, nullable=true)
*/
private $fleetNumber;

/**
* @var string|null
* @ORM\Column(name="FM_ID", type="string", length=20, nullable=true)
*/
private $fmId;

// ...
}

Расширенный класс транспортных средств

<?php
// src/AppBundle/Entity/VehicleFox.php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FoxBundle\Entity\Vehicle as BaseVehicle;
use AppBundle\Model\VehicleInterface;
use Doctrine\Common\Collections\ArrayCollection;

/**
* @ORM\Entity
* @ORM\Table(name="vehicle_fox")
*/
class VehicleFox extends BaseVehicle implements VehicleInterface
{

/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @var string|null
* @ORM\Column(name="fleet_number", type="string", length=20, nullable=true)
*/
private $fleetNumber;

/**
* @var string|null
* @ORM\Column(name="FM_ID", type="string", length=20, nullable=true)
*/
private $fmId;

/**
* @ORM\OneToMany(targetEntity="FM_Positions", mappedBy="truck")
*/
private $fm_positions;
}

Интерфейс автомобиля

<?php
// src/AppBundle/Model/VehicleInterface.php

namespace AppBundle\Model;

interface VehicleInterface
{

public function __construct();
/**
* @return string
*/
public function getId();
public function addTruckUnit(\AppBundle\Entity\Truck_Units $truckUnit);
public function removeTruckUnit(\AppBundle\Entity\Truck_Units $truckUnit);
public function getTruckUnits();
public function addFmPosition(\AppBundle\Entity\FM_Positions $fmPosition);
public function removeFmPosition(\AppBundle\Entity\FM_Positions $fmPosition);
public function getFmPositions();
public function addFmTrip(\AppBundle\Entity\FM_Trips $fmTrip);
public function removeFmTrip(\AppBundle\Entity\FM_Trips $fmTrip);
public function getFmTrips();
public function addSkytrackPosition(\AppBundle\Entity\Skytrack_Positions $skytrackPosition);
public function removeSkytrackPosition(\AppBundle\Entity\Skytrack_Positions $skytrackPosition);
public function getSkytrackPositions();

}

config.yml

doctrine:
# ...
orm:
resolve_target_entities:
AppBundle\Model\VehicleInterface: AppBundle\Entity\VehicleFox
auto_generate_proxy_classes: "%kernel.debug%"default_entity_manager: maxem
entity_managers:
maxem:
connection: maxdb
mappings:
AppBundle:
foxem:
connection: foxdb
mappings:
FoxBundle: ~

Форма FMPositionType

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;

class FM_PositionsType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('position_id')
->add('truck_id', EntityType::class, Array(
'class' => 'FoxBundle:Vehicle',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('v')
->orderBy('v.fleetNumber', 'ASC');
},
'placeholder' => 'Select A Truck',
'choice_label' => 'fleetNumber',
'em' => 'foxem',
))
->add('driver_id', EntityType::class, Array(
'class' => 'MaxBundle:UdoDriver',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('d')
->orderBy('d.nickname', 'ASC');
},
'placeholder' => 'Select A Driver',
'choice_label' => 'nickname',
'em' => 'max2em',
))
->add('date')
->add('latitude')
->add('longitude')
->add('heading')
->add('speed')
->add('altitude');
}

/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\FM_Positions'
));
}

/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_fm_positions';
}}

2

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector