For my project, I have a workspace (kind of a user) with many projects and I am wondering if there is a way to override the default Doctrine query for when I call $workspace->getProjects() to only fetch the active projects only (not the archived one). This way I won't have to filter my collection and it will reduce the size of the returned data from the database.
/**
* Acme\DemoBundle\Entity\Workspace
*
* #ORM\Table()
* #ORM\Entity
*/
class Workspace {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
private $id;
/**
* #var ArrayCollection $projects
*
* #ORM\OneToMany(targetEntity="Project", mappedBy="workspace")
*/
private $projects;
/**
* Add projects
*
* #param Project $projects
* #return Workspace
*/
public function addProject( Project $projects ) {
$this->projects[] = $projects;
return $this;
}
/**
* Remove projects
*
* #param Project $projects
*/
public function removeProject( Project $projects ) {
$this->projects->removeElement( $projects );
}
/**
* Get projects
*
* #return Collection
*/
public function getProjects() {
return $this->projects;
}
You will have to write your own method in the Entity Repository Class.
http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
To do that, you can use criteria.
Here is an exemple from the doctrine doc, to adapt to your needs
use Doctrine\Common\Collections\Criteria;
$criteria = Criteria::create()
->where(Criteria::expr()->eq("birthday", "1982-02-17"))
->orderBy(array("username" => Criteria::ASC))
->setFirstResult(0)
->setMaxResults(20)
;
$birthdayUsers = $object-getUsers()->matching($criteria);
You can create some listener, and catch doctrine events: http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/event-listeners.html
And modify your query before execute as you wish;
Example from Doctrine docs, for custom hook on delete:
<?php
class UserListener extends Doctrine_EventListener
{
/**
* Skip the normal delete options so we can override it with our own
*
* #param Doctrine_Event $event
* #return void
*/
public function preDelete( Doctrine_Event $event )
{
$event->skipOperation();
}
/**
* Implement postDelete() hook and set the deleted flag to true
*
* #param Doctrine_Event $event
* #return void
*/
public function postDelete( Doctrine_Event $event )
{
$name = $this->_options['name'];
$event->getInvoker()->$name = true;
$event->getInvoker()->save();
}
/**
* Implement preDqlDelete() hook and modify a dql delete query so it updates the deleted flag
* instead of deleting the record
*
* #param Doctrine_Event $event
* #return void
*/
public function preDqlDelete( Doctrine_Event $event )
{
$params = $event->getParams();
$field = $params['alias'] . '.deleted';
$q = $event->getQuery();
if ( ! $q->contains( $field ) )
{
$q->from('')->update( $params['component'] . ' ' . $params['alias'] );
$q->set( $field, '?', array(false) );
$q->addWhere( $field . ' = ?', array(true) );
}
}
/**
* Implement preDqlDelete() hook and add the deleted flag to all queries for which this model
* is being used in.
*
* #param Doctrine_Event $event
* #return void
*/
public function preDqlSelect( Doctrine_Event $event )
{
$params = $event->getParams();
$field = $params['alias'] . '.deleted';
$q = $event->getQuery();
if ( ! $q->contains( $field ) )
{
$q->addWhere( $field . ' = ?', array(false) );
}
}
}
I think you can put your logic inside the getter method itself
public function getProjects() {
$filtered_projects = array()
foreach($this->projects as $project)
{
// Your logic here
// e.g.
// if($project->getIsActive()){
// $filtered_projects[] = $project;
// }
}
return $filtered_projects;
}
Related
I already had a question regarding "importing" records and there data of different plugins/extensions. I got it working after adding the pid and implemented a query builder to get the data of a different plugin (or table in this case). But now I got the problem that the images of the "foreign" table/records or whatever is not included.. when I debug the var the image is only set to int 1. But they are not correctly included. What do I need to do to get this s*** working? :)
//MY CONTROLLER
<?php
namespace Formschoen\Mitarbeiterajax\Controller;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* MitarbeiterController
*/
class MitarbeiterController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
/**
* mitarbeiterRepository
*
* #var \Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository
*/
protected $mitarbeiterRepository = null;
/**
* #param \Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository $mitarbeiterRepository
*/
public function injectMitarbeiterRepository(\Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository $mitarbeiterRepository)
{
$this->mitarbeiterRepository = $mitarbeiterRepository;
}
/**
* optionRecordRepository
*
* #var \Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository
*/
protected $optionRecordRepository;
/**
* #param \Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository
*/
public function injectOptionRecordRepository(\Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository $optionRecordRepository) {
$this->optionRecordRepository = $optionRecordRepository;
}
/**
* action list
*
* #return void
*/
public function listAction()
{
$mitarbeiters = $this->mitarbeiterRepository->findAll();
$this->view->assign('mitarbeiters', $mitarbeiters);
$this->view->assign("currentPageID", $GLOBALS['TSFE']->id);
$options['autohaus'] = array(
1 => 'some strings'
);
$options['abteilung'] = array(
1 => 'some strings'
);
$this->view->assign('options', $options);
}
/**
* action callAjax
*
* #param \Formschoen\Mitarbeiterajax\Domain\Model\Mitarbeiter $mitarbeiter
* #return void
*/
public function callAjaxAction(\Formschoen\Mitarbeiterajax\Domain\Model\Mitarbeiter $mitarbeiter)
{
$optionRecords = $this->optionRecordRepository->findAll();
$arguments = $this->request->getArguments();
$selectedAutohaus = $arguments['autohaus'];
$selectedAbteilung = $arguments['abteilung'];
if ($selectedAbteilung == null && $selectedAutohaus == null) {
echo("Bitte ein Autohaus auswählen / eine Abteilung.");
} else if ($selectedAbteilung == null) {
$autohausResult = $this->mitarbeiterRepository->findAutohaus($selectedAutohaus);
$this->view->assign('autohausResult', $autohausResult);
} else {
$mitarbeiterResult = $this->mitarbeiterRepository->findByFilter($selectedAutohaus, $selectedAbteilung);
$this->view->assign('mitarbeiterResult', $mitarbeiterResult);
}
$this->contentObj = $this->configurationManager->getContentObject();
$images=$this->getFileReferences($this->contentObj->data['uid']);
$this->view->assign('images', $images);
}
}
//MY REPOSITORY
<?php
namespace Formschoen\Mitarbeiterajax\Domain\Repository;
/**
* The repository for Mitarbeiters
*/
class MitarbeiterRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
/**
* #param $selectedAutohaus
* #param $selectedAbteilung
*/
public function findByFilter($selectedAutohaus,$selectedAbteilung){
$query = $this->createQuery();
$result = $query->matching($query->logicalAnd(
$query->equals('autohausName', $selectedAutohaus),
$query->equals('abteilung', $selectedAbteilung)
))
->execute();
return $result;
}
/**
* #param $uid
*/
public function findAutohaus($uid)
{
$queryBuilder = $this->objectManager->get(\TYPO3\CMS\Core\Database\ConnectionPool::class)
->getConnectionForTable('tx_ajaxselectlist_domain_model_optionrecord')->createQueryBuilder();
$queryBuilder
->select('*')
->from('tx_ajaxselectlist_domain_model_optionrecord')
->where(
$queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid))
);
$result = $queryBuilder->execute()->fetchAll();
if ($returnRawQueryResult) {
$dataMapper = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper::class);
return $dataMapper->map($this->objectType, $result);
}
return $result;
}
}
Why dont you just replace this
$autohausResult = $this->mitarbeiterRepository->findAutohaus($selectedAutohaus);
with this
$autohausResult = $this->optionRecordRepository->findByUid($selectedAutohaus);
This way TYPO3 will construct the Models and you will get the image they way you want it
I have a variety of custom shipping methods in my store, but I noticed that, if the user is logged in, the order cannot be finished. The user chooses which shipping method they want and then they cannot pass the payment method, because it keeps giving this error: Please specify a shipping method.
Here's my code:
Model/Carrier/CustomShipping.php
<?php
namespace Magenticians\Moduleshipping\Model\Carrier;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\DataObject;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Config;
use Magento\Shipping\Model\Rate\ResultFactory;
use Magento\Store\Model\ScopeInterface;
use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory;
use Magento\Quote\Model\Quote\Address\RateResult\Method;
use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Psr\Log\LoggerInterface;
class Customshipping extends AbstractCarrier implements CarrierInterface
{
/**
* Carrier's code
*
* #var string
*/
protected $_code = 'magenticians_moduleshipping';
/**
* Whether this carrier has fixed rates calculation
*
* #var bool
*/
protected $_isFixed = true;
/**
* #var ResultFactory
*/
protected $_rateResultFactory;
/**
* #var MethodFactory
*/
protected $_rateMethodFactory;
/**
* #param ScopeConfigInterface $scopeConfig
* #param ErrorFactory $rateErrorFactory
* #param LoggerInterface $logger
* #param ResultFactory $rateResultFactory
* #param MethodFactory $rateMethodFactory
* #param array $data
*/
public function __construct(
ScopeConfigInterface $scopeConfig,
ErrorFactory $rateErrorFactory,
LoggerInterface $logger,
ResultFactory $rateResultFactory,
MethodFactory $rateMethodFactory,
array $data = []
) {
$this->_rateResultFactory = $rateResultFactory;
$this->_rateMethodFactory = $rateMethodFactory;
parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
}
/**
* Generates list of allowed carrier's shipping methods
* Displays on cart price rules page
*
* #return array
* #api
*/
public function getAllowedMethods()
{
return [$this->getCarrierCode() => __($this->getConfigData('name'))];
}
/**
* Collect and get rates for storefront
*
* #SuppressWarnings(PHPMD.UnusedFormalParameter)
* #param RateRequest $request
* #return DataObject|bool|null
* #api
*/
public function collectRates(RateRequest $request)
{
/**
* Make sure that Shipping method is enabled
*/
if (!$this->isActive()) {
return false;
}
$weight = 0;
if ($request->getAllItems())
{
foreach ($request->getAllItems() as $item)
{
if ($item->getProduct()->isVirtual())
{
continue;
}
if ($item->getHasChildren())
{
foreach ($item->getChildren() as $child)
{
if (! $child->getProduct()->isVirtual())
{
$weight += $child->getWeight();
}
}
} else
{
$weight += $item->getWeight();
}
}
}
$final_weight = $weight;
/** #var \Magento\Shipping\Model\Rate\Result $result */
$result = $this->_rateResultFactory->create();
$shippingPrice = $this->getConfigData('price');
$method = $this->_rateMethodFactory->create();
/**
* Set carrier's method data
*/
$method->setCarrier($this->getCarrierCode());
$method->setCarrierTitle($this->getConfigData('title'));
/**
* Displayed as shipping method under Carrier
*/
$method->setMethod($this->getCarrierCode());
$method->setMethodTitle($this->getConfigData('name'));
$method->setPrice($shippingPrice);
$method->setCost($shippingPrice);
if($final_weight <= 2) {
$result->append($method);
}
return $result;
}
}
Can't seem to find a reason why, I compared my code with others and they look pretty much identical.
Thanks in advance.
Seems magento 2.2 is not loving underscore on attribute $_code.
$_code = 'magenticians_moduleshipping';
Try change to
protected $_code = 'magenticiansmoduleshipping';
I am trying to insert data into db ,but it shows some error like this
My model Entity
Request.php
is here `<?php
namespace EvolisClientRequest\Model\Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Request
{
/**
* #var \Ramsey\Uuid\Uuid
* #ORM\Id
* #ORM\Column(type="uuid")
* #ORM\GeneratedValue(strategy="CUSTOM")
* #ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Salesperson", inversedBy="request")
* #ORM\JoinTable(name="request_salesperson")
* #var Salesperson
*/
private $salesperson;
/**
* #ORM\ManyToOne(targetEntity="Client", inversedBy="request")
* #var Client
*/
private $client;
/**
* #ORM\ManyToMany(targetEntity="Status", inversedBy="request")
* #ORM\JoinTable(name="request_status")
* #var Status
*/
private $status;
/**
* #ORM\Column(type="integer")
* #var Qualification
*/
private $qualification;
/**
* #return \Ramsey\Uuid\Uuid
*/
public function getId()
{
return $this->id;
}
/**
* #return Salesperson
*/
public function getSalesperson()
{
return $this->salesperson;
}
/**
* #param Salesperson $salesperson
*/
public function setSalesperson($salesperson)
{
$this->salesperson = $salesperson;
}
/**
* #return Client
*/
public function getClient()
{
return $this->client;
}
/**
* #param Client $client
*/
public function setClient($client)
{
$this->client = $client;
}
/**
* #return Status
*/
public function getStatus()
{
return $this->status;
}
/**
* #param Status $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* #return Qualification
*/
public function getQualification()
{
return $this->qualification;
}
/**
* #param Qualification $qualification
*/
public function setQualification($qualification)
{
$this->qualification = $qualification;
}
public function __construct($salesperson, $client, $status, $qualification) {
$this->salesperson = $salesperson;
$this->client = $client;
$this->status = $status;
$this->qualification = $qualification;
}
}`
Also my
DAO "RequestBaseDao.php" is here,which is automatically generated.
<?php
/*
* This file has been automatically generated by Mouf/ORM.
* DO NOT edit this file, as it might be overwritten.
* If you need to perform changes, edit the RequestDao class instead!
*/
namespace EvolisClientRequest\Model\DAOs;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NonUniqueResultException;
use Mouf\Doctrine\ORM\Event\SaveListenerInterface;
use EvolisClientRequest\Model\Entities\Request;
/**
* The RequestBaseDao class will maintain the persistence of Request class into the request table.
*
* #method Request findByQualification($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneByQualification($fieldValue, $orderBy = null)
* #method Request findBySurfaceMin($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneBySurfaceMin($fieldValue, $orderBy = null)
* #method Request findBySurfaceMax($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneBySurfaceMax($fieldValue, $orderBy = null)
* #method Request findByPriceMin($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneByPriceMin($fieldValue, $orderBy = null)
* #method Request findByPriceMax($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneByPriceMax($fieldValue, $orderBy = null)
* #method Request findByRequestDate($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneByRequestDate($fieldValue, $orderBy = null)
*/
class RequestBaseDao extends EntityRepository
{
/**
* #var SaveListenerInterface[]
*/
private $saveListenerCollection;
/**
* #param EntityManagerInterface $entityManager
* #param SaveListenerInterface[] $saveListenerCollection
*/
public function __construct(EntityManagerInterface $entityManager, array $saveListenerCollection = [])
{
parent::__construct($entityManager, $entityManager->getClassMetadata('EvolisClientRequest\Model\Entities\Request'));
$this->saveListenerCollection = $saveListenerCollection;
}
/**
* Get a new persistent entity
* #param ...$params
* #return Request
*/
public function create(...$params) : Request
{
$entity = new Request(...$params);
$this->getEntityManager()->persist($entity);
return $entity;
}
/**
* Peforms a flush on the entity.
*
* #param Request
* #throws \Exception
*/
public function save(Request $entity)
{
foreach ($this->saveListenerCollection as $saveListener) {
$saveListener->preSave($entity);
}
$this->getEntityManager()->flush($entity);
foreach ($this->saveListenerCollection as $saveListener) {
$saveListener->postSave($entity);
}
}
/**
* Peforms remove on the entity.
*
* #param Request $entity
*/
public function remove(Request $entity)
{
$this->getEntityManager()->remove($entity);
}
/**
* Finds only one entity. The criteria must contain all the elements needed to find a unique entity.
* Throw an exception if more than one entity was found.
*
* #param array $criteria
*
* #return Request
*/
public function findUniqueBy(array $criteria) : Request
{
$result = $this->findBy($criteria);
if (count($result) === 1) {
return $result[0];
} elseif (count($result) > 1) {
throw new NonUniqueResultException('More than one Request was found');
} else {
return;
}
}
/**
* Finds only one entity by Qualification.
* Throw an exception if more than one entity was found.
*
* #param mixed $fieldValue the value of the filtered field
*
* #return Request
*/
public function findUniqueByQualification($fieldValue)
{
return $this->findUniqueBy(array('qualification' => $fieldValue));
}
}
My RequestDao.php where i can write queries.
<?php
namespace EvolisClientRequest\Model\DAOs;
use EvolisClientRequest\Model\Entities\Request;
/**
* The RequestDao class will maintain the persistence of Request class into the request table.
*/
class RequestDao extends RequestBaseDao {
/*** PUT YOUR SPECIFIC QUERIES HERE !! ***/
public function setdata()
{
/*$product = new Request();
$product->setStatus('Keyboard');
$product->setClient('000000001ae10dda000000003c4667a6');
$product->setSalesperson('Ergonomic and stylish!');
$product->setQualification('1111');
//var_dump($r);die();
$em = $this->getEntityManager();
$em->persist($product);
$em->flush();*/
$product= $this->create('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111');
$this->save($product);
}
}
Finally my Controller "ContactController.php"
<?php
namespace EvolisClientRequest\Controllers;
use EvolisClientRequest\Model\DAOs\ClientDao;
use EvolisClientRequest\Model\Entities\Client;
use EvolisClientRequest\Model\Entities\Clients;
use EvolisClientRequest\Model\DAOs\RequestDao;
use EvolisClientRequest\Model\Entities\Request;
use EvolisClientRequest\Model\Entities\Requests;
use EvolisClientRequest\Model\DAOs\SalespersonDao;
use EvolisClientRequest\Model\Entities\Salesperson;
use EvolisClientRequest\Model\Entities\Salespersons;
use Mouf\Mvc\Splash\Annotations\Get;
use Mouf\Mvc\Splash\Annotations\Post;
use Mouf\Mvc\Splash\Annotations\Put;
use Mouf\Mvc\Splash\Annotations\Delete;
use Mouf\Mvc\Splash\Annotations\URL;
use Mouf\Html\Template\TemplateInterface;
use Mouf\Html\HtmlElement\HtmlBlock;
use Psr\Log\LoggerInterface;
use \Twig_Environment;
use Mouf\Html\Renderer\Twig\TwigTemplate;
use Mouf\Mvc\Splash\HtmlResponse;
use Doctrine\DBAL\DriverManager;
use Zend\Diactoros\Response\JsonResponse;
use Doctrine\Common\Collections\ArrayCollection;
/**
* TODO: write controller comment
*/
class ContactController {
/**
* The logger used by this controller.
* #var LoggerInterface
*/
private $logger;
/**
* The template used by this controller.
* #var TemplateInterface
*/
private $template;
/**
* The header of the page.
* #var HtmlBlock
*/
private $header;
/**
* The main content block of the page.
* #var HtmlBlock
*/
private $content;
/**
* The Twig environment (used to render Twig templates).
* #var Twig_Environment
*/
private $twig;
/**
* Controller's constructor.
* #param LoggerInterface $logger The logger
* #param TemplateInterface $template The template used by this controller
* #param HtmlBlock $content The main content block of the page
* #param Twig_Environment $twig The Twig environment (used to render Twig templates)
*/
public function __construct(LoggerInterface $logger, TemplateInterface $template, HtmlBlock $content, HtmlBlock $header, Twig_Environment $twig, ClientDao $clientDao, RequestDao $requestDao, SalespersonDao $salespersonDao) {
$this->logger = $logger;
$this->template = $template;
$this->content = $content;
$this->twig = $twig;
$this->header = $header;
$this->clientDao = $clientDao;
$this->requestDao = $requestDao;
$this->salespersonDao = $salespersonDao;
}
/**
* #URL("new.html")
*/
public function new() {
// TODO: write content of action here
// Let's add the twig file to the template.
$this->content->addHtmlElement(new TwigTemplate($this->twig, 'views/contact/new.twig', array("message"=>"world")));
$this->header->addHtmlElement(new TwigTemplate($this->twig, 'views/root/header.twig', array("message"=>"world")));
return new HtmlResponse($this->template);
}
/**
* #URL("saveData")
* For Saving the data
*/
public function saveData()
{
/*$newClient = $this->clientDao->create('hello', 'sarathchandran#122.com','8907263949');
$this->clientDao->save($newClient);*/
//$data = array();
//$data['salespersonDao']['salesperson'] = 'example#sales.com';
//$data['request']['qualification'] = 'abcdefgh';
//$newClient = $this->requestDao->create($data);
//$newClient = $this->requestDao->setQualification('Keyboard');
// $this->requestDao->save($newClient);
$user_data=$this->requestDao->setdata();
//return new JsonResponse([ "status"=>0 ]);
}
}
I am using Mouf framework.I am stuck with this problem.Someone Please help me to solve this problem.
Thanks in advance
As advised by #rokas, you should really start reading more about Doctrine. This is not a Mouf issue, this is clearly a Doctrine ORM issue so the appropriate doc is here: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/index.html
Here are a few tips:
Your controller calls the setdata method
$user_data=$this->requestDao->setdata();
The setdata method calls:
$product= $this->create('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111');
Now, the create method is:
public function create(...$params) : Request
{
$entity = new Request(...$params);
$this->getEntityManager()->persist($entity);
return $entity;
}
This means that it will call the Request constructor with this parameters:
$entity = new Request('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111');
Have a look at the Request constructor:
public function __construct($salesperson, $client, $status, $qualification) {
$this->salesperson = $salesperson;
$this->client = $client;
$this->status = $status;
$this->qualification = $qualification;
}
As you can see, the first parameter is $salesperson. You try to put the value "Keyboard" here. The $salesperson attribute is defined this way:
/**
* #ORM\ManyToMany(targetEntity="Salesperson", inversedBy="request")
* #ORM\JoinTable(name="request_salesperson")
* #var Salesperson
*/
private $salesperson;
/**
* #param Salesperson $salesperson
*/
public function setSalesperson($salesperson)
{
$this->salesperson = $salesperson;
}
Now, here is your problem I think.
The $salesperson property is defined as a "ManyToMany" association. So you really cannot put a string in here, it is a collection of Salesperson. By the way, you should not "set" anything either. The setter should be completely removed.
Instead, you should consider using it as per the documentation here: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html
For instance:
$request->getSalesPersons()->add($someObjectRepresentingAPerson);
Also, notice that since the $salesperson represents a collection of Salesperson object, your should really name it $salesPersons (plural form)
This describes my current schema:
/**
* #MongoDB\Document(repositoryClass="St\AppBundle\Repository\TaxiStateRepository", requireIndexes=true)
* #MongoDB\Index(keys={"location"="2d"})
*/
class TaxiState
{
/**
* #MongoDB\ReferenceOne(targetDocument="Taxi", simple=true, inversedBy="taxiState")
* #MongoDB\Index
*/
protected $taxi;
..
}
/**
* #MongoDB\Document(repositoryClass="St\AppBundle\Repository\TaxiRepository", requireIndexes=true)
*/
class Taxi
{
/**
* #MongoDB\ReferenceOne(targetDocument="Driver", simple=true)
* #MongoDB\Index
*/
protected $driver;
..
}
/**
* #MongoDB\Document(repositoryClass="St\AppBundle\Repository\DriverRepository", requireIndexes=true)
*/
class Driver
{
/**
* #MongoDB\EmbedOne(targetDocument="DriverAccount")
* #MongoDB\Index
*/
protected $driverAccount;
..
}
/** #MongoDB\EmbeddedDocument */
class DriverAccount
{
/**
* #MongoDB\String
* #Assert\NotBlank()
* #Assert\Choice(choices = {"enabled","disabled"}, message="please chose a valid status"); * #MongoDB\Index
*/
protected $status;
I basically want to run a query that filters out disabled driver accounts.. something like this:
return $this->createQueryBuilder()
->field('taxi.driver.driverAccount.status')->equals("enabled")
->getQuery()
->getSingleResult();
it complains that it doesn't have an index taxi.driver etc.. I spent all day looking at by directional reference documentation in doctrine but the examples are so sparse.. help?
For reference.. this was the query that worked right before i introduced that crazy line:
return $this->createQueryBuilder()
->field('status')->equals('available')
->field('taxi')->notIn($taxiObj)
->field('location')->near((float)$location->getLongitude(), (float)$location->getLatitude())
->distanceMultiplier(self::EARTH_RADIUS_KM)
->maxDistance($radius/111.12)
->getQuery()
->execute();
Just in case you were wondering how I "resolved" this (it's a very hacky answer.. but oh well you do what you gotta do right?) this is what I got:
/**
* Find near enabled taxi without rejected request taxi
*
* #param Document\Location $location
* #param int $radius
* #param array $taxis
* #return Document\TaxiState
*/
public function findEnabledNearTaxiWithoutRejectRequest(Document\Location $location, $radius = self::SEARCH_RADIUS, $taxis = array(), $logger)
{
$taxiObj = array_map(function ($item) {
return new \MongoId($item);
}, $taxis);
//ST-135 change to near, spherical, distanceMultiplier and maxDistance in KM
$allTaxiStates = $this->createQueryBuilder()
->field('status')->equals('available')
->field('taxi')->notIn($taxiObj)
->field('location')->near((float)$location->getLongitude(), (float)$location->getLatitude())
->distanceMultiplier(self::EARTH_RADIUS_KM)
->maxDistance($radius/111.12)
->getQuery()
->execute();
$this->addIdsOfDisabledTaxiStates($taxiObj, $allTaxiStates);
if (count($taxiObj) > 0) {
$logger->info("There are ".count($taxiObj)." taxis excluded while looking for taxis to respond to a requst: ".$this->getMongoIdsStr($taxiObj));
}
return $this->createQueryBuilder()
->field('status')->equals('available')
->field('taxi')->notIn($taxiObj)
->field('location')->near((float)$location->getLongitude(), (float)$location->getLatitude())
->distanceMultiplier(self::EARTH_RADIUS_KM)
->maxDistance($radius/111.12)
->getQuery()
->getSingleResult();
}
/**
* Get the Mongo Ids of disabled taxi States
*
* #param $ids existing array of ids we want to append to (passed by reference)
* #param $taxiStates array of Document\TaxiState
* #return array of MongoIds of disabled taxi states
* #author Abdullah
*/
private function addIdsOfDisabledTaxiStates(&$ids, $taxiStates)
{
foreach ($taxiStates as $taxiState) {
if ($taxiState->getTaxi()->getDriver()->getDriverAccount()->getStatus() != DriverAccountModel::STATUS_ENABLED) {
$mongoId = new \MongoId($taxiState->getTaxi()->getId());
array_push($ids, $mongoId);
}
}
return $ids;
}
I've FabricanteDistribuidor.php entity with this code:
/**
* #ORM\Entity
* #ORM\Table(name="nomencladores.fabricante_distribuidor", schema="nomencladores")
* #ORM\Entity(repositoryClass="AppBundle\Entity\Repository\FabricanteDistribuidorRepository")
* #UniqueEntity(fields={"nombre"}, message="El nombre ya está registrado")
*/
class FabricanteDistribuidor
{
use IdentifierAutogeneratedEntityTrait;
use NamedEntityTrait;
// ... some other fields
/**
* #ORM\ManyToMany(targetEntity="Sencamer\AppBundle\Entity\Pais")
* #ORM\JoinTable(name="negocio.fabricante_distribuidor_pais", schema="negocio",
* joinColumns={#ORM\JoinColumn(name="fabricante_distribuidor", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="pais_id", referencedColumnName="id")}
* )
*/
protected $paises;
/**
* Set paises
*
* #param \AppBundle\Entity\Pais $pais
* #return FabricanteDistribuidor
*/
public function setPaises(\AppBundle\Entity\Pais $pais)
{
$this->paises[] = $pais;
return $this;
}
/**
* Get paises
*
* #return string
*/
public function getPaises()
{
return $this->paises;
}
}
Then in the controller I'm trying to get one records and it associated like in this case will be all the paises as follow:
public function obtenerDetallesFabricanteAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:FabricanteDistribuidor')->find($request->query->get('id'));
if ($request->isXmlHttpRequest()) {
$response['entities'] = array();
$dataResponse = array();
// ... some other fields
$dataResponse['paises'] = $entity->getPaises();
$response['entities'][] = $dataResponse;
return new JsonResponse($response);
}
}
In the JSON response I get everything fine but paises is set to NULL and the relation table fabricante_distribuidor_pais has value for the fabricante I'm seek, why? What I'm doing wrong in the ManyToMany relationship?
I watch in dev.log and join is never made:
doctrine.DEBUG: SELECT t0.direccion AS direccion1, t0.telefono AS
telefono2, t0.fax AS fax3, t0.correo AS correo4, t0.id AS id5,
t0.nombre AS nombre6 FROM nomencladores.fabricante_distribuidor t0
WHERE t0.id = ? ["1"] []
Why?
Solution and some concerns around it
After read and read and do a intensive research through Stackoverflow, Google and so on I get the solution, it working, I do not know if is the best of if it's right so you tell me:
FabricanteDistribuidor.php
class FabricanteDistribuidor
{
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Pais", mappedBy="fabricanteDistribuidor", cascade={"persist"})
*/
private $paises;
/**
* Set paises
*
* #param \AppBundle\Entity\Pais $pais
* #return FabricanteDistribuidor
*/
public function setPaises(\Sencamer\AppBundle\Entity\Pais $pais)
{
$this->paises[] = $pais;
return $this;
}
/**
* Get paises
*
* #return Doctrine\Common\Collections\Collection
*/
public function getPaises()
{
return $this->paises;
}
}
Pais.php
class Pais
{
use IdentifierAutogeneratedEntityTrait;
use NamedEntityTrait;
use ActiveEntityTrait;
/**
* #ORM\ManyToMany(targetEntity="Sencamer\AppBundle\Entity\FabricanteDistribuidor", inversedBy="paises", cascade={"persist"})
* #ORM\JoinTable(name="negocio.fabricante_distribuidor_pais", schema="negocio",
* joinColumns={#ORM\JoinColumn(name="fabricante_distribuidor", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="pais_id", referencedColumnName="id")}
* )
*/
protected $fabricanteDistribuidor;
/**
* Add fabricanteDistribuidor
*
* #param AppBundle\Entity\FabricanteDistribuidor $fabricanteDistribuidor
*/
public function addfabricanteDistribuidor(\AppBundle\Entity\FabricanteDistribuidor $fabricanteDistribuidor)
{
$this->fabricanteDistribuidor[] = $fabricanteDistribuidor;
}
/**
* Get fabricanteDistribuidor
*
* #return Doctrine\Common\Collections\Collection
*/
public function getfabricanteDistribuidor()
{
return $this->fabricanteDistribuidor;
}
}
Then in my controller I iterate over the request looking for each pais I want to add and flush it when the object is persisted:
if ($fabricanteDistribuidorForm->isValid()) {
try {
$em->persist($fabricanteDistribuidorEntity);
$em->flush();
$formDataPais = $request->get('fabricanteDistribuidor')['pais'];
foreach ($formDataPais as $paisId) {
$pais = $em->getRepository('AppBundle:Pais')->find($paisId);
$fabricanteDistribuidorEntity->setPaises($pais);
$em->flush();
}
$response['entities'][] = $dataResponse;
} catch (Exception $ex) {
$response['success'] = FALSE;
$response['error'] = $ex->getMessage();
}
} else {
return $this->getFormErrors($fabricanteDistribuidorForm); ;
}
That way all works fine and data is persisted in the right way. Now around this solution I have another issue and a concern. The issue is that I'm trying to get now the related paises from FabricanteDistribuidoras follow and I'm doing something wrong since I can't get their names, so what is wrong in my code?
public function obtenerDetallesFabricanteAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:FabricanteDistribuidor')->find($request->query->get('id'));
if ($request->isXmlHttpRequest()) {
$response['entities'] = array();
$dataResponse = array();
// rest of columns ....
if ($entity->getPaises() instanceof Pais) {
$paises = array();
foreach ($entity->getPaises() as $pais) {
$paises[] = $pais->getNombre();
}
$dataResponse['paises'] = $paises;
}
$response['entities'][] = $dataResponse;
return new JsonResponse($response);
}
}
The concern is around the Pais class as you notice I added the inversed side $fabricanteDistribuidor so, do I have to insert this any time I want to insert a new Pais or is just to tell Doctrine how to deal with proxies inside it? I've not clear yet how owning/inversed side works yet maybe due to this I did thing as my code shown. Any advice around this too?
my n-m realtions are like this:
/**
* #ORM\ManyToMany(targetEntity="Sencamer\AppBundle\Entity\Pais")
* #ORM\JoinTable(name="negocio.fabricante_distribuidor_pais", schema="negocio",
* joinColumns={#ORM\JoinColumn(name="fabricante_distribuidor_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="pais_id", referencedColumnName="id")}
* )
*/
check if in your join sentence, the "fabricante_distribuidor" is a "id".
And remember, you need to put in your constructor to set the "paises" like arrayCollection:
public function __construct() {
$this->paises = new \Doctrine\Common\Collections\ArrayCollection();
}
and in the n-m relationship is a good practice create addPaises and not setPaises:
public function addPais(\AppBundle\Entity\Pais $pais){
$this->paises[] = $pais;
return $this;
}
I think, somewhere in your code you add the "paises" to your "fabricante.distribuidor", isn't it?
I hope that helps you