Im trying to write this query in symfony2 with queryBuilder() but i get an syntax error [Syntax Error] line 0, col 58: Error: Expected end of string, got 'SELECT'
SELECT * FROM upload_video as p ORDER BY (SELECT COUNT(*) FROM vote as v WHERE v.video_id = p.id ) DESC;
So can anyone help me convert this query into Symfony2 doctrine format
$qb->createQuery("SELECT p FROM HotelPlanBundle:UploadVideo as p ORDER BY (SELECT COUNT(v) FROM HotelPlanBundle:Vote v WHERE v.video_id = p.id ) desc");
this is the UploadVideo entity
namespace HotelPlanBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
/**
* UploadVideo
*
* #ORM\Table(name="upload_video")
* #ORM\Entity(repositoryClass="HotelPlanBundle\Repository\UploadVideoRepository")
* #ORM\HasLifecycleCallbacks
*/
class UploadVideo
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
private $file;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255, nullable=true)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="path", type="text", nullable=true)
*/
private $path;
/**
* #var string
*
* #ORM\Column(name="video_path", type="text", nullable=true)
*/
private $videoPath;
/**
* #var \DateTime
*
* #ORM\Column(name="created_date", type="datetime")
*/
private $createdDate;
/**
* #var boolean
*
* #ORM\Column(name="is_approved", type="boolean")
*/
private $isApproved;
/**
* #var \DateTime
* #ORM\Column(name="approved_date", type="datetime", nullable=true)
*/
private $approvedDate;
/**
* #ORM\OneToMany( targetEntity="HotelPlanBundle\Entity\Vote", mappedBy="videoId", cascade={"all"}, orphanRemoval=true )
* #ORM\OrderBy({"id" = "ASC"})
*/
protected $votes;
/**
* #var integer
* #ORM\Column(name="is_winner", type="boolean")
*/
private $isWinner;
/**
* #var integer
* #ORM\Column(name="views", type="integer")
*/
private $views;
/**
* #var boolean
* #ORM\Column(name="is_deleted", type="boolean")
*/
private $isDeleted;
/**
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $userId;
/**
* #var string
*
* #ORM\Column(name="status", type="string", length=255, nullable=true)
* #ORM\ManyToOne(targetEntity="VideoStatus")
* #ORM\JoinColumn(name="is_approved", referencedColumnName="id")
*/
private $status;
/**
* #return null|string
* #ORM\Column(name="link", type="string", length=255, unique=true)
*/
private $link;
/**
* #var
* #ORM\Column(name="thumbnail", type="string", length=100, nullable=true)
*/
private $thumbnail;
/**
* #return null|string
* #ORM\Column(name="resetlink", type="string", length=255, nullable=true)
*/
private $resetLink;
public function __construct()
{
$this->setIsWinner( FALSE );
$this->setIsDeleted( FALSE );
$this->setIsApproved( FALSE );
$this->votes = new ArrayCollection();
}
public function getAbsolutePath()
{
return NULL === $this->path
? NULL
: $this->getUploadRootDir() . '/' . $this->path;
}
public function getWebPath()
{
return NULL === $this->path
? NULL
: $this->getUploadDir() . '/' . $this->path;
}
public function getWebThumbnail()
{
return '/uploads/documents' . '/' . $this->getThumbnail();
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
return __DIR__ . '/../../../web/' . $this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'uploads/documents';
}
public function upload()
{
// the file property can be empty if the field is not required
if ( NULL === $this->getFile() ) {
return;
}
// use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and then the
// target filename to move to
$this->getFile()->move(
$this->getUploadRootDir(),
$this->getFile()->getClientOriginalName()
);
// set the path property to the filename where you've saved the file
$this->path = $this->getFile()->getClientOriginalName();
// clean up the file property as you won't need it anymore
$this->file = NULL;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return UploadVideo
*/
public function setTitle( $title )
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set file
*
* #param string $file
* #return UploadVideo
*/
public function setFile( $file )
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return string
*/
public function getFile()
{
return $this->file;
}
/**
* Set path
*
* #param string $path
* #return UploadVideo
*/
public function setPath( $path )
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set videoPath
*
* #param string $videoPath
* #return UploadVideo
*/
public function setVideoPath( $videoPath )
{
$this->videoPath = $videoPath;
return $this;
}
/**
* Get videoPath
*
* #return string
*/
public function getVideoPath()
{
return $this->videoPath;
}
/**
* Set createdDate
*
* #param \DateTime $createdDate
* #return UploadVideo
*/
public function setCreatedDate( $createdDate )
{
$this->createdDate = $createdDate;
return $this;
}
/**
* Get createdDate
*
* #return \DateTime
*/
public function getCreatedDate()
{
return $this->createdDate;
}
/**
* Set isApproved
*
* #param boolean $isApproved
* #return UploadVideo
*/
public function setIsApproved( $isApproved )
{
$this->isApproved = $isApproved;
return $this;
}
/**
* Get isApproved
*
* #return boolean
*/
public function getIsApproved()
{
return $this->isApproved;
}
/**
* Set approvedDate
*
* #param \DateTime $approvedDate
* #return UploadVideo
*/
public function setApprovedDate( $approvedDate )
{
$this->approvedDate = $approvedDate;
return $this;
}
/**
* Get approvedDate
*
* #return \DateTime
*/
public function getApprovedDate()
{
return $this->approvedDate;
}
/**
* Set isWinner
*
* #param boolean $isWinner
* #return UploadVideo
*/
public function setIsWinner( $isWinner )
{
$this->isWinner = $isWinner;
return $this;
}
/**
* Get isWinner
*
* #return boolean
*/
public function getIsWinner()
{
return $this->isWinner;
}
/**
* Set isDeleted
*
* #param boolean $isDeleted
* #return UploadVideo
*/
public function setIsDeleted( $isDeleted )
{
$this->isDeleted = $isDeleted;
return $this;
}
/**
* Get isDeleted
*
* #return boolean
*/
public function getIsDeleted()
{
return $this->isDeleted;
}
/**
* Set status
*
* #param string $status
* #return UploadVideo
*/
public function setStatus( $status )
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set link
*
* #param string $link
* #return UploadVideo
*/
public function setLink( $link )
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set thumbnail
*
* #param string $thumbnail
* #return UploadVideo
*/
public function setThumbnail( $thumbnail )
{
$this->thumbnail = $thumbnail;
return $this;
}
/**
* Get thumbnail
*
* #return string
*/
public function getThumbnail()
{
return $this->thumbnail;
}
/**
* Set resetLink
*
* #param string $resetLink
* #return UploadVideo
*/
public function setResetLink( $resetLink )
{
$this->resetLink = $resetLink;
return $this;
}
/**
* Get resetLink
*
* #return string
*/
public function getResetLink()
{
return $this->resetLink;
}
/**
* Add votes
*
* #param \HotelPlanBundle\Entity\Vote $votes
* #return UploadVideo
*/
public function addVote( \HotelPlanBundle\Entity\Vote $votes )
{
$this->votes[] = $votes;
return $this;
}
/**
* Remove votes
*
* #param \HotelPlanBundle\Entity\Vote $votes
*/
public function removeVote( \HotelPlanBundle\Entity\Vote $votes )
{
$this->votes->removeElement( $votes );
}
/**
* Get votes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVotes()
{
return $this->votes;
}
/**
* Set userId
*
* #param \HotelPlanBundle\Entity\User $userId
* #return UploadVideo
*/
public function setUserId( \HotelPlanBundle\Entity\User $userId = NULL )
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return \HotelPlanBundle\Entity\User
*/
public function getUserId()
{
return $this->userId;
}
/**
* Set views
*
* #param integer $views
* #return UploadVideo
*/
public function setViews($views)
{
$this->views = $views;
return $this;
}
/**
* Get views
*
* #return integer
*/
public function getViews()
{
return $this->views;
}
}
`This is the Vote entity
namespace HotelPlanBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Vote
*
* #ORM\Table(name="vote")
* #ORM\Entity(repositoryClass="HotelPlanBundle\Repository\VoteRepository")
*/
class Vote
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="Likes")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $userId;
/**
* #var int
*
* #ORM\ManyToOne(targetEntity="HotelPlanBundle\Entity\UploadVideo", inversedBy="votes", cascade={"persist"})
* #ORM\JoinColumn(name="video_id", referencedColumnName="id")
*
*/
private $videoId;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Vote
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set userId
*
* #param \HotelPlanBundle\Entity\User $userId
* #return Vote
*/
public function setUserId(\HotelPlanBundle\Entity\User $userId = null)
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return \HotelPlanBundle\Entity\User
*/
public function getUserId()
{
return $this->userId;
}
/**
* Set videoId
*
* #param \HotelPlanBundle\Entity\UploadVideo $videoId
* #return Vote
*/
public function setVideoId(\HotelPlanBundle\Entity\UploadVideo $videoId = null)
{
$this->videoId = $videoId;
return $this;
}
/**
* Get videoId
*
* #return \HotelPlanBundle\Entity\UploadVideo
*/
public function getVideoId()
{
return $this->videoId;
}
}
What i'm trying to do is i'm trying to order the videos based on the votes that are in the vote table or in the collection.
You can use QueryBuilder to achieve that:
$qb = $em->createQueryBuilder();
$result = $qb->select('uv, COUNT(v) AS HIDDEN votesCount')
->from('HotelPlanBundle\Entity\UploadVideo', 'uv')
->leftJoin('uv.votes', 'v')
->where('v.videoId = uv.id')
->orderBy('votesCount', 'DESC')
->groupBy('uv')
->getQuery()
->getResult();
or if you want to use DQL:
$em->createQuery('SELECT uv, COUNT(v) as AS HIDDEN votesCount FROM HotelPlanBundle\Entity\UploadVideo uv LEFT JOIN uv.votes v WHERE v.videoId = uv.id GROUP BY uv ORDER BY votesCount DESC');
Related
I'm trying to upgrade an application running on Symfony 3.4 to version 4.4. I already did multiple changes and adaptions according to the official documentation for upgrading Symfony. Neverthelesse, I'm stuck now with the following error that comes up when I try to run a command in the terminal or access the application via browser.
Mapping Exception
Doctrine\ORM\Mapping\MappingException:
The target-entity App\DocumentBundle\File cannot be found in 'App\DocumentBundle\Entity\Document#file'.
at /srv/http/sp7/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php:772
at Doctrine\ORM\Mapping\MappingException::invalidTargetEntityClass('App\\DocumentBundle\\File', 'App\\DocumentBundle\\Entity\\Document', 'file')
(/srv/http/sp7/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:1032)
at Doctrine\ORM\Mapping\ClassMetadataInfo->validateAssociations()
(/srv/http/sp7/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:266)
at Doctrine\ORM\Mapping\ClassMetadataFactory->validateRuntimeMetadata(object(ClassMetadata), object(ClassMetadata))
(/srv/http/sp7/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:245)
at Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata(object(ClassMetadata), object(ClassMetadata), false, array())
(/srv/http/sp7/vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/AbstractClassMetadataFactory.php:306)
at Doctrine\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata('App\\DocumentBundle\\Entity\\Document')
(/srv/http/sp7/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:78)
at Doctrine\ORM\Mapping\ClassMetadataFactory->loadMetadata('App\\DocumentBundle\\Entity\\Document')
(/srv/http/sp7/vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/AbstractClassMetadataFactory.php:185)
at Doctrine\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor('App\\DocumentBundle\\Entity\\Document')
(/srv/http/sp7/vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/AbstractClassMetadataFactory.php:91)
at Doctrine\Persistence\Mapping\AbstractClassMetadataFactory->getAllMetadata()
(/srv/http/sp7/vendor/mgilet/notification-bundle/NotifiableDiscovery.php:76)
at Mgilet\NotificationBundle\NotifiableDiscovery->discoverNotifiables()
(/srv/http/sp7/vendor/mgilet/notification-bundle/NotifiableDiscovery.php:40)
at Mgilet\NotificationBundle\NotifiableDiscovery->__construct(object(EntityManager), object(CachedReader))
(/srv/http/sp7/var/cache/dev/ContainerSAZB8iG/srcApp_KernelDevDebugContainer.php:6135)
at ContainerSAZB8iG\srcApp_KernelDevDebugContainer->getMgilet_NotificationService()
(/srv/http/sp7/var/cache/dev/ContainerSAZB8iG/srcApp_KernelDevDebugContainer.php:7481)
at ContainerSAZB8iG\srcApp_KernelDevDebugContainer->getTwigService()
(/srv/http/sp7/var/cache/dev/ContainerSAZB8iG/srcApp_KernelDevDebugContainer.php:13406)
at ContainerSAZB8iG\srcApp_KernelDevDebugContainer->getSensioFrameworkExtra_View_ListenerService()
(/srv/http/sp7/var/cache/dev/ContainerSAZB8iG/srcApp_KernelDevDebugContainer.php:4501)
at ContainerSAZB8iG\srcApp_KernelDevDebugContainer->ContainerSAZB8iG\{closure}()
(/srv/http/sp7/vendor/symfony/event-dispatcher/EventDispatcher.php:301)
at Symfony\Component\EventDispatcher\EventDispatcher::Symfony\Component\EventDispatcher\{closure}(object(ControllerEvent), 'kernel.controller', object(EventDispatcher))
(/srv/http/sp7/vendor/symfony/event-dispatcher/EventDispatcher.php:264)
at Symfony\Component\EventDispatcher\EventDispatcher->doDispatch(array(object(Closure), object(Closure), object(Closure), object(Closure), object(Closure), object(Closure)), 'kernel.controller', object(ControllerEvent))
(/srv/http/sp7/vendor/symfony/event-dispatcher/EventDispatcher.php:239)
at Symfony\Component\EventDispatcher\EventDispatcher->callListeners(array(object(Closure), object(Closure), object(Closure), object(Closure), object(Closure), object(Closure)), 'kernel.controller', object(ControllerEvent))
(/srv/http/sp7/vendor/symfony/event-dispatcher/EventDispatcher.php:73)
at Symfony\Component\EventDispatcher\EventDispatcher->dispatch(object(ControllerEvent), 'kernel.controller')
(/srv/http/sp7/vendor/symfony/http-kernel/HttpKernel.php:134)
at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
(/srv/http/sp7/vendor/symfony/http-kernel/HttpKernel.php:68)
at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
(/srv/http/sp7/vendor/symfony/http-kernel/Kernel.php:201)
at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
(/srv/http/sp7/public/index.php:25)
The code itself should store a document and offer the possibility to attach files to the documents. Therefore, I used the Vich/Uploader-Bundle and I suspect that the error somehow is linked to Vich.
Document.php
<?php
namespace App\DocumentBundle\Entity;
use App\Entity\FileAwareEntity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Security;
use App\UserBundle\Entity\User as User;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="document_document", options={"engine"="InnoDB"})
* #ORM\Entity(repositoryClass="App\DocumentBundle\Entity\DocumentRepository")
*/
class Document extends FileAwareEntity {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #Assert\NotBlank()
* #var string
* #ORM\Column(type="string")
* #Groups({"elastica"})
*/
private $name;
/**
*
* #var string
* #ORM\Column(type="text", nullable=true)
* #Groups({"elastica"})
*/
private $description;
/**
*
* #var string
* #ORM\Column(type="string", nullable=true)
* #Groups({"elastica"})
*/
private $headline;
/**
* #ORM\ManyToOne(targetEntity="App\DocumentBundle\Entity\DocumentType")
* #ORM\JoinColumn(name="type", referencedColumnName="id")
* #ORM\OrderBy({"translationKey" = "ASC"})
* #var \App\DocumentBundle\Entity\DocumentType
* #Groups({"elastica"})
**/
private $type;
/**
* #var string
* #ORM\Column(type="string", nullable=true)
* #Groups({"elastica"})
*/
private $vkaNumber;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $linkedDocument;
/**
* #var string
* #ORM\Column(type="string", nullable=true)
*/
private $linkedDocumentExpires;
/**
* #var boolean
* #ORM\Column(type="boolean", nullable=true)
* #Groups({"elastica"})
*/
private $active;
/**
* #var boolean
* #ORM\Column(type="boolean", nullable=true)
*/
private $status_stealth;
/**
* #var boolean
* #ORM\Column(type="boolean", nullable=true)
*/
private $locked;
/**
* $var DateTime
* #ORM\Column(type="datetime", nullable=true)
* #Groups({"elastica"})
*/
private $created;
// * #Groups({"elastica"})
/**
* #ORM\ManyToOne(targetEntity="App\UserBundle\Entity\User", inversedBy="documentsCreated")
* #ORM\JoinColumn(name="createdBy", referencedColumnName="id")
* #var \App\UserBundle\Entity\User
**/
private $createdBy;
/**
* $var DateTime
* #ORM\Column(type="datetime", nullable=true)
* #Assert\Expression(
* "false == this.getStealthException()",
* message="The effective date must be in the future!")
* #Groups({"elastica"})
*/
private $effective;
/**
* $var DateTime
* #ORM\Column(type="datetime", nullable=true)
* #Assert\Expression(
* "this.getEffective() < this.getExpires()",
* message="The expiration date can't be before the effective date")
*/
private $expires;
/**
* $var DateTime
* #ORM\Column(type="datetime", nullable=true)
*/
private $modified;
/**
* #ORM\ManyToOne(targetEntity="App\UserBundle\Entity\User")
* #ORM\JoinColumn(name="modifiedBy", referencedColumnName="id")
* #var \App\UserBundle\Entity\User
**/
private $modifiedBy;
// * #Groups({"elastica"})
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Agency", inversedBy="documentagency", cascade={"persist"})
* #ORM\JoinTable(name="document_document_agency",
* joinColumns={#ORM\JoinColumn(name="document_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="iata8", referencedColumnName="iata8")})
* #var \App\Entity\Agency
**/
private $agency;
/**
* $var boolean
* #ORM\Column(type="boolean", nullable=true)
*/
private $signature;
/**
* $var boolean
* #ORM\Column(type="boolean", nullable=true)
*/
private $signed;
/**
* #ORM\ManyToOne(targetEntity="App\UserBundle\Entity\User", inversedBy="documentSigned")
* #ORM\JoinColumn(name="signedBy", referencedColumnName="id")
* #var \App\UserBundle\Entity\User
**/
private $signedBy;
/**
* #ORM\OneToMany(targetEntity="App\DocumentBundle\Entity\Comment", mappedBy="document",cascade={"remove"})
* #var \Doctrine\Common\Collections\Collection
**/
protected $comment;
// * #Groups({"elastica"})
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Market", inversedBy="document", cascade={"persist"})
* #ORM\JoinTable(name="document_document_market",
* joinColumns={#ORM\JoinColumn(name="document_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="market_id", referencedColumnName="id")})
* #Assert\Count(
* min = "0"
* )
**/
private $market;
// * #Groups({"elastica"})
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Airline", inversedBy="document", cascade={"persist"})
* #ORM\JoinTable(name="document_document_airline",
* joinColumns={#ORM\JoinColumn(name="document_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="airline_id", referencedColumnName="id")})
* #Assert\Count(
* min = "0"
* )
* #var \App\Entity\Airline
**/
private $airline;
// * #Groups({"elastica"})
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Product", inversedBy="document", cascade={"persist"})
* #ORM\JoinTable(name="document_document_product",
* joinColumns={#ORM\JoinColumn(name="document_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="product_id", referencedColumnName="id")})
* #Assert\Count(
* min = "0"
* )
* #var \App\Entity\Product
**/
private $product;
// * #Groups({"elastica"})
/**
* #ORM\ManyToMany(targetEntity="App\ReferentialBundle\Entity\Channel1", inversedBy="document", cascade={"persist"})
* #ORM\JoinTable(name="document_document_channel",
* joinColumns={#ORM\JoinColumn(name="document_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="channel_id", referencedColumnName="id")})
* #Assert\Count(
* min = "0"
* )
* #var \App\ReferentialBundle\Entity\Channel1
**/
private $channel;
/**
* $var boolean
* #ORM\Column(type="boolean", nullable=true)
*/
private $internalCom;
/**
* #ORM\OneToMany(targetEntity="App\DocumentBundle\File", mappedBy="entity", cascade={"persist", "merge", "remove"}, orphanRemoval=true)
* #Assert\Valid()
* #var \Doctrine\Common\Collections\Collection
**/
protected $file;
/**
* #ORM\ManyToOne(targetEntity="App\DocumentBundle\Entity\Status")
* #ORM\JoinColumn(name="status", referencedColumnName="id", nullable=false)
* #var \App\DocumentBundle\Entity\Status
* #Groups({"elastica"})
*/
private $status;
/**
* #ORM\ManyToMany(targetEntity="App\DocumentBundle\Entity\UploadProfile", inversedBy="documents", cascade={"persist"})
* #ORM\JoinTable(name="document_document_uploadprofile",
* joinColumns={#ORM\JoinColumn(name="document_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="uploadprofile_id", referencedColumnName="id")})
* #var \App\DocumentBundle\Entity\UploadProfile
**/
protected $uploadprofile;
/**
* #ORM\Column(type="decimal", precision=7, scale=7, nullable = true)
*/
protected $esScore;
/**
* Constructor
*/
public function __construct()
{
$this->locked = false;
$this->signed = false;
$this->market = new \Doctrine\Common\Collections\ArrayCollection();
$this->agency = new \Doctrine\Common\Collections\ArrayCollection();
$this->channel = new \Doctrine\Common\Collections\ArrayCollection();
$this->product = new \Doctrine\Common\Collections\ArrayCollection();
}
/* Entity: Functions ************************************************************************/
public function getCurrentDate(){
return new \DateTime();
}
/**
* #ORM\PrePersist
*/
public function prePersist() {
date_default_timezone_set('Europe/Berlin');
if($this->created == null)
{
$this->created = new \DateTime("now");
}
$market = $this->getMarket();
if(count($this->getAgency()) > 0){
foreach($this->getAgency() as $agency) {
if(!$this->market->contains($agency->getMarket())) {
$this->addMarket($agency->getMarket());
}
}
}
}
/**
* #ORM\PreUpdate
*/
public function preUpdate() {
date_default_timezone_set('Europe/Berlin');
if($this->modified == null)
{
$this->modified = new \DateTime("now");
}
$market = $this->getMarket();
if(count($this->getAgency()) > 0){
foreach($this->getAgency() as $agency) {
if(!$this->market->contains($agency->getMarket())) {
$this->addMarket($agency->getMarket());
}
}
}
}
/**
* Get statusStealth
*
* #return boolean
*/
public function getStatusStealth()
{
return $this->status_stealth;
}
public function getStealthException(){
if ($this->getEffective() < $this->getCurrentDate() && $this->getStatusStealth() == true){
return true;
} else{
return false;
}
}
public function show()
{
return array(
"domain" => "document",
"id" => $this->id,
"info" => $this->getHeadline(),
"title" => $this->name . ' - ' . $this->vkaNumber,
"airlines" => $this->getAirline(),
"agencies" => $this->getAgency(),
"markets" => $this->getMarket(),
"vkaNumber" => $this->vkaNumber,
"path" => "documentBundle_view_document",
"pathVariable" => "id",
"pathValue" => $this->id,
"bootstrapColor" => 'primary',
);
}
/* Entity: Functions ************************************************************************/
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Document
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
*
* #return Document
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set headline
*
* #param string $headline
*
* #return Document
*/
public function setHeadline($headline)
{
$this->headline = $headline;
return $this;
}
/**
* Get headline
*
* #return string
*/
public function getHeadline()
{
return $this->headline;
}
/**
* Set vkaNumber
*
* #param string $vkaNumber
*
* #return Document
*/
public function setVkaNumber($vkaNumber)
{
$this->vkaNumber = $vkaNumber;
return $this;
}
/**
* Get vkaNumber
*
* #return string
*/
public function getVkaNumber()
{
return $this->vkaNumber;
}
/**
* Set linkedDocument
*
* #param string $linkedDocument
*
* #return Document
*/
public function setLinkedDocument($linkedDocument)
{
$this->linkedDocument = $linkedDocument;
return $this;
}
/**
* Get linkedDocument
*
* #return string
*/
public function getLinkedDocument()
{
return $this->linkedDocument;
}
/**
* Set linkedDocumentExpires
*
* #param string $linkedDocumentExpires
*
* #return Document
*/
public function setLinkedDocumentExpires($linkedDocumentExpires)
{
$this->linkedDocumentExpires = $linkedDocumentExpires;
return $this;
}
/**
* Get linkedDocumentExpires
*
* #return string
*/
public function getLinkedDocumentExpires()
{
return $this->linkedDocumentExpires;
}
/**
* Set active
*
* #param boolean $active
*
* #return Document
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
* Get active
*
* #return boolean
*/
public function getActive()
{
return $this->active;
}
/**
* Set statusStealth
*
* #param boolean $statusStealth
*
* #return Document
*/
public function setStatusStealth($statusStealth)
{
$this->status_stealth = $statusStealth;
return $this;
}
/**
* Set locked
*
* #param boolean $locked
*
* #return Document
*/
public function setLocked($locked)
{
$this->locked = $locked;
return $this;
}
/**
* Get locked
*
* #return boolean
*/
public function getLocked()
{
return $this->locked;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return Document
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set effective
*
* #param \DateTime $effective
*
* #return Document
*/
public function setEffective($effective)
{
$this->effective = $effective;
return $this;
}
/**
* Get effective
*
* #return \DateTime
*/
public function getEffective()
{
return $this->effective;
}
/**
* Set expires
*
* #param \DateTime $expires
*
* #return Document
*/
public function setExpires($expires)
{
$this->expires = $expires;
return $this;
}
/**
* Get expires
*
* #return \DateTime
*/
public function getExpires()
{
return $this->expires;
}
/**
* Set modified
*
* #param \DateTime $modified
*
* #return Document
*/
public function setModified($modified)
{
$this->modified = $modified;
return $this;
}
/**
* Get modified
*
* #return \DateTime
*/
public function getModified()
{
return $this->modified;
}
/**
* Set signature
*
* #param boolean $signature
*
* #return Document
*/
public function setSignature($signature)
{
$this->signature = $signature;
return $this;
}
/**
* Get signature
*
* #return boolean
*/
public function getSignature()
{
return $this->signature;
}
/**
* Set signed
*
* #param boolean $signed
*
* #return Document
*/
public function setSigned($signed)
{
$this->signed = $signed;
return $this;
}
/**
* Get signed
*
* #return boolean
*/
public function getSigned()
{
return $this->signed;
}
/**
* Set internalCom
*
* #param boolean $internalCom
*
* #return Document
*/
public function setInternalCom($internalCom)
{
$this->internalCom = $internalCom;
return $this;
}
/**
* Get internalCom
*
* #return boolean
*/
public function getInternalCom()
{
return $this->internalCom;
}
/**
* Set esScore
*
* #param string $esScore
*
* #return Document
*/
public function setEsScore($esScore)
{
$this->esScore = $esScore;
return $this;
}
/**
* Get esScore
*
* #return string
*/
public function getEsScore()
{
return $this->esScore;
}
/**
* Set type
*
* #param \App\DocumentBundle\Entity\DocumentType $type
*
* #return Document
*/
public function setType(\App\DocumentBundle\Entity\DocumentType $type = null)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return \App\DocumentBundle\Entity\DocumentType
*/
public function getType()
{
return $this->type;
}
/**
* Set createdBy
*
* #param \App\UserBundle\Entity\User $createdBy
*
* #return Document
*/
public function setCreatedBy(\App\UserBundle\Entity\User $createdBy = null)
{
$this->createdBy = $createdBy;
return $this;
}
/**
* Get createdBy
*
* #return \App\UserBundle\Entity\User
*/
public function getCreatedBy()
{
return $this->createdBy;
}
/**
* Set modifiedBy
*
* #param \App\UserBundle\Entity\User $modifiedBy
*
* #return Document
*/
public function setModifiedBy(\App\UserBundle\Entity\User $modifiedBy = null)
{
$this->modifiedBy = $modifiedBy;
return $this;
}
/**
* Get modifiedBy
*
* #return \App\UserBundle\Entity\User
*/
public function getModifiedBy()
{
return $this->modifiedBy;
}
/**
* Add agency
*
* #param \App\Entity\Agency $agency
*
* #return Document
*/
public function addAgency(\App\Entity\Agency $agency)
{
$this->agency[] = $agency;
return $this;
}
/**
* Remove agency
*
* #param \App\Entity\Agency $agency
*/
public function removeAgency(\App\Entity\Agency $agency)
{
$this->agency->removeElement($agency);
}
/**
* Get agency
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAgency()
{
return $this->agency;
}
/**
* Set signedBy
*
* #param \App\UserBundle\Entity\User $signedBy
*
* #return Document
*/
public function setSignedBy(\App\UserBundle\Entity\User $signedBy = null)
{
$this->signedBy = $signedBy;
return $this;
}
/**
* Get signedBy
*
* #return \App\UserBundle\Entity\User
*/
public function getSignedBy()
{
return $this->signedBy;
}
/**
* Add comment
*
* #param \App\DocumentBundle\Entity\Comment $comment
*
* #return Document
*/
public function addComment(\App\DocumentBundle\Entity\Comment $comment)
{
$this->comment[] = $comment;
return $this;
}
/**
* Remove comment
*
* #param \App\DocumentBundle\Entity\Comment $comment
*/
public function removeComment(\App\DocumentBundle\Entity\Comment $comment)
{
$this->comment->removeElement($comment);
}
/**
* Get comment
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getComment()
{
return $this->comment;
}
/**
* Add market
*
* #param \App\Entity\Market $market
*
* #return Document
*/
public function addMarket(\App\Entity\Market $market)
{
$this->market[] = $market;
return $this;
}
/**
* Remove market
*
* #param \App\Entity\Market $market
*/
public function removeMarket(\App\Entity\Market $market)
{
$this->market->removeElement($market);
}
/**
* Get market
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMarket()
{
return $this->market;
}
/**
* Add airline
*
* #param \App\Entity\Airline $airline
*
* #return Document
*/
public function addAirline(\App\Entity\Airline $airline)
{
$this->airline[] = $airline;
return $this;
}
/**
* Remove airline
*
* #param \App\Entity\Airline $airline
*/
public function removeAirline(\App\Entity\Airline $airline)
{
$this->airline->removeElement($airline);
}
/**
* Get airline
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAirline()
{
return $this->airline;
}
/**
* Add product
*
* #param \App\Entity\Product $product
*
* #return Document
*/
public function addProduct(\App\Entity\Product $product)
{
$this->product[] = $product;
return $this;
}
/**
* Remove product
*
* #param \App\Entity\Product $product
*/
public function removeProduct(\App\Entity\Product $product)
{
$this->product->removeElement($product);
}
/**
* Get product
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProduct()
{
return $this->product;
}
/**
* Add channel
*
* #param \App\ReferentialBundle\Entity\Channel1 $channel
*
* #return Document
*/
public function addChannel(\App\ReferentialBundle\Entity\Channel1 $channel)
{
$this->channel[] = $channel;
return $this;
}
/**
* Remove channel
*
* #param \App\ReferentialBundle\Entity\Channel1 $channel
*/
public function removeChannel(\App\ReferentialBundle\Entity\Channel1 $channel)
{
$this->channel->removeElement($channel);
}
/**
* Get channel
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChannel()
{
return $this->channel;
}
/**
* Get file
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFile()
{
return $this->file;
}
}
File.php (child class)
<?php
namespace App\DocumentBundle;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\File as BaseFile;
/**
* This class extends the base file class. Only the mapped entity and table name are different.
*
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="document_file")
* #ORM\Entity
*/
class File extends BaseFile {
/**
* #ORM\ManyToOne(targetEntity="App\DocumentBundle\Entity\Document", inversedBy="file")
* #ORM\JoinColumn(name="entity", referencedColumnName="id", nullable=true)
* #var \App\DocumentBundle\Entity\Document
*/
protected $entity;
}
I already tried to clean the cache, restart the server, update doctrine or commented the property out, but nothing has worked so far. Has anyone an idea how to ressolve this issue?
I have three tables and two relations. One table is many to many and the other table is one to many relation. I created a query in mysql but I'm not converting to dql or querybuilder in Symfony.
Sample query is:
SELECT * FROM `resturant` LEFT JOIN `food` ON `resturant`.`id` = `food`.`resturant_id`
WHERE `food`.`name` LIKE "%pizza%"
GROUP BY `resturant`.`name`
food entity in my project
<?php
namespace Food\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Food
*
* #ORM\Table(name="food")
* #ORM\Entity(repositoryClass="Food\AdminBundle\Repository\FoodRepository")
*/
class Food
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="contents", type="string", length=500, nullable=true)
*/
private $contents;
/**
* #var string
*
* #ORM\Column(name="price", type="integer", nullable=true)
*/
private $price;
/**
* #var bool
*
* #ORM\Column(name="approve", type="boolean")
*/
private $approve;
/**
* #var \Food\AdminBundle\Entity\Category
*
* #ORM\ManyToOne(targetEntity="Food\AdminBundle\Entity\Category")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="CASCADE" )
* })
*/
private $category;
/**
* #var \Food\AdminBundle\Entity\Resturant
*
* #ORM\ManyToOne(targetEntity="Food\AdminBundle\Entity\Resturant")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="resturant_id", referencedColumnName="id", onDelete="CASCADE" )
* })
*/
private $resturant;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Food
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set contents
*
* #param string $contents
*
* #return Food
*/
public function setContents($contents)
{
$this->contents = $contents;
return $this;
}
/**
* Get contents
*
* #return string
*/
public function getContents()
{
return $this->contents;
}
/**
* Set approve
*
* #param boolean $approve
*
* #return Food
*/
public function setApprove($approve)
{
$this->approve = $approve;
return $this;
}
/**
* Get approve
*
* #return bool
*/
public function getApprove()
{
return $this->approve;
}
/**
* Set category
*
* #param \Food\AdminBundle\Entity\Category $category
*
* #return Food
*/
public function setCategory(\Food\AdminBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \Food\AdminBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Set resturant
*
* #param \Food\AdminBundle\Entity\Resturant $resturant
*
* #return Food
*/
public function setResturant(\Food\AdminBundle\Entity\Resturant $resturant = null)
{
$this->resturant = $resturant;
return $this;
}
/**
* Get resturant
*
* #return \Food\AdminBundle\Entity\Resturant
*/
public function getResturant()
{
return $this->resturant;
}
/**
* Set price
*
* #param integer $price
*
* #return Food
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return integer
*/
public function getPrice()
{
return $this->price;
}
}
Resturant entity
<?php
namespace Food\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* Resturant
*
* #ORM\Table(name="resturant")
* #ORM\Entity(repositoryClass="Food\AdminBundle\Repository\ResturantRepository")
*/
class Resturant
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="logo", type="string", length=30, nullable=true)
*/
private $logo;
/**
* #var string
*
* #ORM\Column(name="duration", type="string", length=150, nullable=true)
*/
private $duration;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=800, nullable=true)
*/
private $address;
/**
* #var int
*
* #ORM\Column(name="minimal", type="integer")
*/
private $minimal;
/**
* #var int
*
* #ORM\Column(name="delivery", type="integer")
*/
private $delivery;
/**
* #var int
*
* #ORM\Column(name="score", type="integer", nullable=true)
*/
private $score;
/**
* #var int
*
* #ORM\Column(name="cost", type="integer")
*/
private $cost;
/**
* #var int
*
* #ORM\Column(name="startlunch", type="time", nullable=true)
*/
private $startlunch;
/**
* #var int
*
* #ORM\Column(name="endlunch", type="time", nullable=true)
*/
private $endlunch;
/**
* #var int
*
* #ORM\Column(name="startdinner", type="time", nullable=true)
*/
private $startdinner;
/**
* #var int
*
* #ORM\Column(name="enddinner", type="time", nullable=true)
*/
private $enddinner;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Food\AdminBundle\Entity\Zone", inversedBy="Resturant")
* #ORM\JoinTable(name="resturant_has_zone",
* joinColumns={
* #ORM\JoinColumn(name="resturant_id", referencedColumnName="id" )
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="zone_id", referencedColumnName="id" )
* }
* )
*/
private $zone;
/**
* #ORM\OneToMany(targetEntity="Food\AdminBundle\Entity\Food", mappedBy="Resturant")
*/
private $food;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Resturant
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set logo
*
* #param string $logo
*
* #return Resturant
*/
public function setLogo($logo)
{
$this->logo = $logo;
return $this;
}
/**
* Get logo
*
* #return string
*/
public function getLogo()
{
return $this->logo;
}
/**
* Set duration
*
* #param string $duration
*
* #return Resturant
*/
public function setDuration($duration)
{
$this->duration = $duration;
return $this;
}
/**
* Get duration
*
* #return string
*/
public function getDuration()
{
return $this->duration;
}
/**
* Set address
*
* #param string $address
*
* #return Resturant
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set minimal
*
* #param integer $minimal
*
* #return Resturant
*/
public function setMinimal($minimal)
{
$this->minimal = $minimal;
return $this;
}
/**
* Get minimal
*
* #return int
*/
public function getMinimal()
{
return $this->minimal;
}
/**
* Set delivery
*
* #param integer $delivery
*
* #return Resturant
*/
public function setDelivery($delivery)
{
$this->delivery = $delivery;
return $this;
}
/**
* Get delivery
*
* #return int
*/
public function getDelivery()
{
return $this->delivery;
}
/**
* Set score
*
* #param integer $score
*
* #return Resturant
*/
public function setScore($score)
{
$this->score = $score;
return $this;
}
/**
* Get score
*
* #return int
*/
public function getScore()
{
return $this->score;
}
/**
* Set cost
*
* #param integer $cost
*
* #return Resturant
*/
public function setCost($cost)
{
$this->cost = $cost;
return $this;
}
/**
* Get cost
*
* #return int
*/
public function getCost()
{
return $this->cost;
}
/**
* Set startlunch
*
* #param \DateTime $startlunch
*
* #return Resturant
*/
public function setStartlunch($startlunch)
{
$this->startlunch = $startlunch;
return $this;
}
/**
* Get startlunch
*
* #return \DateTime
*/
public function getStartlunch()
{
return $this->startlunch;
}
/**
* Set endlunch
*
* #param \DateTime $endlunch
*
* #return Resturant
*/
public function setEndlunch($endlunch)
{
$this->endlunch = $endlunch;
return $this;
}
/**
* Get endlunch
*
* #return \DateTime
*/
public function getEndlunch()
{
return $this->endlunch;
}
/**
* Set startdinner
*
* #param \DateTime $startdinner
*
* #return Resturant
*/
public function setStartdinner($startdinner)
{
$this->startdinner = $startdinner;
return $this;
}
/**
* Get startdinner
*
* #return \DateTime
*/
public function getStartdinner()
{
return $this->startdinner;
}
/**
* Set enddinner
*
* #param \DateTime $enddinner
*
* #return Resturant
*/
public function setEnddinner($enddinner)
{
$this->enddinner = $enddinner;
return $this;
}
/**
* Get enddinner
*
* #return \DateTime
*/
public function getEnddinner()
{
return $this->enddinner;
}
/**
* Constructor
*/
public function __construct()
{
$this->zone = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add zone
*
* #param \Food\AdminBundle\Entity\Zone $zone
*
* #return Resturant
*/
public function addZone(\Food\AdminBundle\Entity\Zone $zone)
{
$this->zone[] = $zone;
return $this;
}
/**
* Remove zone
*
* #param \Food\AdminBundle\Entity\Zone $zone
*/
public function removeZone(\Food\AdminBundle\Entity\Zone $zone)
{
$this->zone->removeElement($zone);
}
/**
* Get zone
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getZone()
{
return $this->zone;
}
/**
* Add food
*
* #param \Food\AdminBundle\Entity\Food $food
*
* #return Resturant
*/
public function addFood(\Food\AdminBundle\Entity\Food $food)
{
$this->food[] = $food;
return $this;
}
/**
* Remove food
*
* #param \Food\AdminBundle\Entity\Food $food
*/
public function removeFood(\Food\AdminBundle\Entity\Food $food)
{
$this->food->removeElement($food);
}
/**
* Get food
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFood()
{
return $this->food;
}
/**
* #Assert\File(
* maxSize="2m",
* mimeTypes = {"image/jpeg", "image/png"},
* mimeTypesMessage = "Please upload a valid Image File"
*
* )
*/
private $file;
// Uploading File LOL
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
public function getAbsolutePath()
{
return null === $this->logo
? null
: $this->getUploadRootDir() . '/' . $this->logo;
}
public function getWebPath()
{
return null === $this->picture
? null
: $this->getUploadDir() . '/' . $this->logo;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'upload/resturant/logo';
}
public function upload()
{
// the file property can be empty if the field is not required
if (null === $this->getFile()) {
return;
}
// use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and then the
// target filename to move to
$stringArray = explode(".", $this->getFile()->getClientOriginalName());
$suffix = $stringArray[count($stringArray) - 1];
$this->logo = $this->random_string() . '.' . $suffix;
$this->getFile()->move(
$this->getUploadRootDir(),
$this->logo
);
// clean up the file property as you won't need it anymore
$this->file = null;
}
private function random_string($hashstring = null, $randLengh = null)
{
$string = $hashstring;
$randLengh = 15;
if ($string == null) {
$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
}
$charactersLength = strlen($string);
$randomString = '';
for ($i = 0; $i < $randLengh; $i++) {
$randomString .= $string[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public function __toString()
{
return $this->getName();
}
}
and zone entity and relation
<?php
namespace Food\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Zone
*
* #ORM\Table(name="zone")
* #ORM\Entity(repositoryClass="Food\AdminBundle\Repository\ZoneRepository")
*/
class Zone
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100, unique=true)
*/
private $name;
/**
* #var bool
*
* #ORM\Column(name="approve", type="boolean")
*/
private $approve;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Zone
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set approve
*
* #param boolean $approve
*
* #return Zone
*/
public function setApprove($approve)
{
$this->approve = $approve;
return $this;
}
/**
* Get approve
*
* #return bool
*/
public function getApprove()
{
return $this->approve;
}
public function __toString()
{
return $this->getName();
}
}
I have below query in MySQL:
SELECT * FROM (orders)
INNER JOIN links ON orders.ref_id = links.id
INNER JOIN users ON links.user_id = users.id
WHERE links.user_id=2
And three entities in Symfony: order, link, user.
How can I write this in Doctrine Query Builder?
$repo = $em->getRepository('OrderBundle:Order');
$queryBuilder=$repo->createQueryBuilder('o');
$query = $queryBuilder
->select('o, l, u')
->innerJoin('c.ref_id', 'l')
->innerJoin('l.user_id', 'u')
->where('u.id=1')
->getQuery();
This doesn't work. I got below error:
[Semantical Error] line 0, col 84 near 'u WHERE u.id': Error: Class OrderBundle\Entity\Order has no association named user_id
I trying for two hours and this make me angry... Thanks in advance.
My order entity:
<?php
// src/OrderBundle/Entity/Order.php
namespace OrderBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\DateTime;
/**
* #ORM\Entity
* #ORM\Table(name="orders")
*/
class Order
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="OrderBundle\Entity\Order")
* #ORM\JoinColumn(name="ref_id", referencedColumnName="id")
*/
protected $ref_id;
/**
* #ORM\Column(type="datetime")
*/
protected $date_created;
/**
* #ORM\Column(type="string", length=60)
*/
protected $email;
/**
* #ORM\Column(type="string", length=60)
*/
protected $email2;
/**
* #ORM\Column(type="integer")
*/
protected $service;
/**
* #ORM\Column(type="string", length=20)
*/
protected $fromlang;
/**
* #ORM\Column(type="string", length=20)
*/
protected $tolang;
/**
* #ORM\Column(type="boolean")
*/
protected $academic;
/**
* #ORM\Column(type="string", length=40)
*/
protected $discipline;
/**
* #ORM\Column(type="text")
*/
protected $notes;
/**
* #ORM\Column(type="string")
*/
protected $file;
/**
* #ORM\Column(type="integer")
*/
protected $status;
/**
* #ORM\Column(type="integer")
*/
protected $cost;
/**
* #ORM\Column(type="string", length=2)
*/
protected $site;
public function __construct()
{
$this->date_created = new DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set dateCreated
*
* #param \DateTime $dateCreated
*
* #return Order
*/
public function setDateCreated($dateCreated)
{
$this->date_created = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->date_created;
}
/**
* Set email
*
* #param string $email
*
* #return Order
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email2
*
* #param string $email2
*
* #return Order
*/
public function setEmail2($email2)
{
$this->email2 = $email2;
return $this;
}
/**
* Get email2
*
* #return string
*/
public function getEmail2()
{
return $this->email2;
}
/**
* Set refId
*
* #param integer $refId
*
* #return Order
*/
public function setRefId($refId)
{
$this->ref_id = $refId;
return $this;
}
/**
* Get refId
*
* #return integer
*/
public function getRefId()
{
return $this->ref_id;
}
/**
* Set service
*
* #param integer $service
*
* #return Order
*/
public function setService($service)
{
$this->service = $service;
return $this;
}
/**
* Get service
*
* #return integer
*/
public function getService()
{
return $this->service;
}
/**
* Set fromlang
*
* #param string $fromlang
*
* #return Order
*/
public function setFromlang($fromlang)
{
$this->fromlang = $fromlang;
return $this;
}
/**
* Get fromlang
*
* #return string
*/
public function getFromlang()
{
return $this->fromlang;
}
/**
* Set tolang
*
* #param string $tolang
*
* #return Order
*/
public function setTolang($tolang)
{
$this->tolang = $tolang;
return $this;
}
/**
* Get tolang
*
* #return string
*/
public function getTolang()
{
return $this->tolang;
}
/**
* Set academic
*
* #param boolean $academic
*
* #return Order
*/
public function setAcademic($academic)
{
$this->academic = $academic;
return $this;
}
/**
* Get academic
*
* #return boolean
*/
public function getAcademic()
{
return $this->academic;
}
/**
* Set discipline
*
* #param string $discipline
*
* #return Order
*/
public function setDiscipline($discipline)
{
$this->discipline = $discipline;
return $this;
}
/**
* Get discipline
*
* #return string
*/
public function getDiscipline()
{
return $this->discipline;
}
/**
* Set notes
*
* #param string $notes
*
* #return Order
*/
public function setNotes($notes)
{
$this->notes = $notes;
return $this;
}
/**
* Get notes
*
* #return string
*/
public function getNotes()
{
return $this->notes;
}
/**
* Set file
*
* #param string $file
*
* #return Order
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return string
*/
public function getFile()
{
return $this->file;
}
/**
* Set status
*
* #param integer $status
*
* #return Order
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set cost
*
* #param integer $cost
*
* #return Order
*/
public function setCost($cost)
{
$this->cost = $cost;
return $this;
}
/**
* Get cost
*
* #return \cost
*/
public function getCost()
{
return $this->cost;
}
/**
* Set site
*
* #param string $site
*
* #return Order
*/
public function setSite($site)
{
$this->site = $site;
return $this;
}
/**
* Get site
*
* #return string
*/
public function getSite()
{
return $this->site;
}
}
I want to find one data with findbyone option but by accesing the related object. Next you'll find the two of the entities Im using.
Caja.php
<?php
namespace PD\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
*
* #ORM\Entity
* #ORM\Table(name="caja")
*
*/
class Caja
{
/**
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Número carton")
*/
protected $numero_carton;
/** #ORM\Column(type="string", length=100) */
protected $contiene_libreta_limite_inferior;
/** #ORM\Column(type="string", length=100) */
protected $contiene_libreta_limite_superior;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Libretas omitidas")
*/
protected $omite_libreta;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Total libretas")
*/
protected $total_libretas;
/** #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Juego")
* #ORM\JoinColumn(name="juego_id", referencedColumnName="id")
* */
protected $juego;
/** #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Usuario") **/
protected $usuario;
/**
* #ORM\Column(type="datetime", nullable=true)
* #GRID\Column(title="Fecha creación")
*/
protected $fecha_creacion;
/**
* #var boolean
*
* #ORM\Column(name="estado", type="string", length=50)
* #GRID\Column(title="Estado")
*/
protected $estado;
/*
* 1 = CREADO
* 2 = ASIGNADO_A_SUPERVISOR
* 3 = FINALIZADO_CON_EXITO
* 4 = FINALIZADO_CON_OBSERVACIONES
* 5 = DESHABILITADO
*
*/
/**
* #ORM\OneToMany(targetEntity="PD\AppBundle\Entity\Libreta", mappedBy="caja", cascade={"remove", "persist"})
*/
protected $libretas;
public function __construct()
{
$this->fecha_creacion = new \DateTime();
$this->libretas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set numero_carton
*
* #param string $numeroCarton
* #return Caja
*/
public function setNumeroCarton($numeroCarton)
{
$this->numero_carton = $numeroCarton;
return $this;
}
/**
* Get numero_carton
*
* #return string
*/
public function getNumeroCarton()
{
return $this->numero_carton;
}
/**
* Set contiene_libreta_limite_inferior
*
* #param string $contieneLibretaLimiteInferior
* #return Caja
*/
public function setContieneLibretaLimiteInferior($contieneLibretaLimiteInferior)
{
$this->contiene_libreta_limite_inferior = $contieneLibretaLimiteInferior;
return $this;
}
/**
* Get contiene_libreta_limite_inferior
*
* #return string
*/
public function getContieneLibretaLimiteInferior()
{
return $this->contiene_libreta_limite_inferior;
}
/**
* Set contiene_libreta_limite_superior
*
* #param string $contieneLibretaLimiteSuperior
* #return Caja
*/
public function setContieneLibretaLimiteSuperior($contieneLibretaLimiteSuperior)
{
$this->contiene_libreta_limite_superior = $contieneLibretaLimiteSuperior;
return $this;
}
/**
* Get contiene_libreta_limite_superior
*
* #return string
*/
public function getContieneLibretaLimiteSuperior()
{
return $this->contiene_libreta_limite_superior;
}
/**
* Set omite_libreta
*
* #param string $omiteLibreta
* #return Caja
*/
public function setOmiteLibreta($omiteLibreta)
{
$this->omite_libreta = $omiteLibreta;
return $this;
}
/**
* Get omite_libreta
*
* #return string
*/
public function getOmiteLibreta()
{
return $this->omite_libreta;
}
/**
* Set total_libretas
*
* #param string $totalLibretas
* #return Caja
*/
public function setTotalLibretas($totalLibretas)
{
$this->total_libretas = $totalLibretas;
return $this;
}
/**
* Get total_libretas
*
* #return string
*/
public function getTotalLibretas()
{
return $this->total_libretas;
}
/**
* Set juego
*
* #param \PD\AppBundle\Entity\Juego $juego
* #return Caja
*/
public function setJuego(\PD\AppBundle\Entity\Juego $juego)
{
$this->juego = $juego;
}
/**
* Get juego
*
* #return \PD\AppBundle\Entity\Juego
*/
public function getJuego()
{
return $this->juego;
}
public function __toString()
{
return $this->getNumeroCarton();
}
/**
* Set usuario
*
* #param \PD\AppBundle\Entity\Usuario $usuario
* #return Caja
*/
public function setUsuario(\PD\AppBundle\Entity\Usuario $usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return \PD\AppBundle\Entity\Usuario
*/
public function getUsuario()
{
return $this->usuario;
}
/**
* Set fecha_creacion
*
* #param \DateTime $fechaCreacion
* #return Caja
*/
public function setFechaCreacion($fechaCreacion)
{
$this->fecha_creacion = $fechaCreacion;
return $this;
}
/**
* Get fecha_creacion
*
* #return \DateTime
*/
public function getFechaCreacion()
{
return $this->fecha_creacion;
}
/**
* Set estado
*
* #param string $estado
* #return Caja
*/
public function setEstado($estado)
{
$this->estado = $estado;
return $this;
}
/**
* Get estado
*
* #return string
*/
public function getEstado()
{
return $this->estado;
}
/**
* Add libretas
*
* #param \PD\AppBundle\Entity\Libreta $libretas
* #return Caja
*/
public function addLibreta(\PD\AppBundle\Entity\Libreta $libretas)
{
//$this->libretas[] = $libretas;
//return $this;
$libretas->setCaja($this);
$this->libretas->add($libretas);
return $this;
}
/**
* Remove libretas
*
* #param \PD\AppBundle\Entity\Libreta $libretas
*/
public function removeLibreta(\PD\AppBundle\Entity\Libreta $libretas)
{
$this->libretas->removeElement($libretas);
}
/**
* Get libretas
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLibretas()
{
return $this->libretas;
}
}
Libreta.php
<?php
namespace PD\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
* Libreta
*
* #ORM\Table()
* #ORM\Entity
*/
class Libreta
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Caja", inversedBy="libretas")
* #ORM\JoinColumn(name="caja_id", referencedColumnName="id", nullable=false)
* #Assert\Type(type="PD\AppBundle\Entity\Caja")
* #GRID\Column(field="caja.juego.nombre", title="Juego")
* #GRID\Column(field="caja.numero_carton", title="Caja")
*/
protected $caja;
/**
* #var string
*
* #ORM\Column(name="correlativo", type="string", length=10)
* #GRID\Column(title="Correlativo")
*/
private $correlativo;
/**
* #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Usuario")
* #ORM\JoinColumn(name="vendedor_id", referencedColumnName="id", nullable=true)
* #Assert\Type(type="PD\AppBundle\Entity\Usuario")
* #GRID\Column(field="vendedor.nombre", title="Nombre vendedor")
* #GRID\Column(field="vendedor.apellidos", title="Apellidos vendedor")
*/
protected $vendedor;
/** #ORM\Column(name="precio_al_vendedor", type="decimal", scale=2) */
protected $precio_al_vendedor;
/** #ORM\Column(name="precio_acumulado", type="decimal", scale=2)
* #GRID\Column(title="Precio acumulado")
*/
protected $precio_acumulado;
/** #ORM\Column(name="premio_acumulado", type="decimal", scale=2)
* #GRID\Column(title="Premio acumulado")
*/
protected $premio_acumulado;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $fecha_asignacion_vendedor;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $fecha_estado_final;
/**
* #ORM\OneToMany(targetEntity="PD\AppBundle\Entity\Ticket", mappedBy="libreta", cascade={"persist"})
*/
protected $tickets;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set correlativo
*
* #param string $correlativo
* #return Libreta
*/
public function setCorrelativo($correlativo)
{
$this->correlativo = $correlativo;
return $this;
}
/**
* Get correlativo
*
* #return string
*/
public function getCorrelativo()
{
return $this->correlativo;
}
/**
* Set precio_al_vendedor
*
* #param string $precioAlVendedor
* #return Libreta
*/
public function setPrecioAlVendedor($precioAlVendedor)
{
$this->precio_al_vendedor = $precioAlVendedor;
return $this;
}
/**
* Get precio_al_vendedor
*
* #return string
*/
public function getPrecioAlVendedor()
{
return $this->precio_al_vendedor;
}
/**
* Set precio_acumulado
*
* #param string $precioAcumulado
* #return Libreta
*/
public function setPrecioAcumulado($precioAcumulado)
{
$this->precio_acumulado = $precioAcumulado;
return $this;
}
/**
* Get precio_acumulado
*
* #return string
*/
public function getPrecioAcumulado()
{
return $this->precio_acumulado;
}
/**
* Set fecha_asignacion_vendedor
*
* #param \DateTime $fechaAsignacionVendedor
* #return Libreta
*/
public function setFechaAsignacionVendedor($fechaAsignacionVendedor)
{
$this->fecha_asignacion_vendedor = $fechaAsignacionVendedor;
return $this;
}
/**
* Get fecha_asignacion_vendedor
*
* #return \DateTime
*/
public function getFechaAsignacionVendedor()
{
return $this->fecha_asignacion_vendedor;
}
/**
* Set fecha_estado_final
*
* #param \DateTime $fechaEstadoFinal
* #return Libreta
*/
public function setFechaEstadoFinal($fechaEstadoFinal)
{
$this->fecha_estado_final = $fechaEstadoFinal;
return $this;
}
/**
* Get fecha_estado_final
*
* #return \DateTime
*/
public function getFechaEstadoFinal()
{
return $this->fecha_estado_final;
}
/**
* Set vendedor
*
* #param \PD\AppBundle\Entity\Usuario $vendedor
* #return Libreta
*/
public function setVendedor(\PD\AppBundle\Entity\Usuario $vendedor = null)
{
$this->vendedor = $vendedor;
return $this;
}
/**
* Get vendedor
*
* #return \PD\AppBundle\Entity\Usuario
*/
public function getVendedor()
{
return $this->vendedor;
}
/**
* Set caja
*
* #param \PD\AppBundle\Entity\Caja $caja
* #return Libreta
*/
public function setCaja(\PD\AppBundle\Entity\Caja $caja = null)
{
$this->caja = $caja;
return $this;
}
/**
* Get caja
*
* #return \PD\AppBundle\Entity\Caja
*/
public function getCaja()
{
return $this->caja;
}
/**
* Constructor
*/
public function __construct()
{
$this->tickets = new \Doctrine\Common\Collections\ArrayCollection();
//$this->caja = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tickets
*
* #param \PD\AppBundle\Entity\Ticket $tickets
* #return Libreta
*/
public function addTicket(\PD\AppBundle\Entity\Ticket $tickets)
{
//$this->tickets[] = $tickets;
$tickets->setLibreta($this);
$this->tickets->add($tickets);
return $this;
}
/**
* Remove tickets
*
* #param \PD\AppBundle\Entity\Ticket $tickets
*/
public function removeTicket(\PD\AppBundle\Entity\Ticket $tickets)
{
$this->tickets->removeElement($tickets);
}
/**
* Get tickets
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTickets()
{
return $this->tickets;
}
public function __toString()
{
return $this->correlativo;
}
/**
* Set premio_acumulado
*
* #param string $premioAcumulado
* #return Libreta
*/
public function setPremioAcumulado($premioAcumulado)
{
$this->premio_acumulado = $premioAcumulado;
return $this;
}
/**
* Get premio_acumulado
*
* #return string
*/
public function getPremioAcumulado()
{
return $this->premio_acumulado;
}
}
And what I would like to do is to find one next row ordered by field "fecha_creacion". This is what I have that get the next row but ordered by caja ID
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findOneBy(array('vendedor' => NULL), array('caja' => 'DESC'));
But what I want to know if I can do something like "array('caja.fecha_creacion' => 'DESC'));". Until now, this part of the code isn't recognizing the "fecha_creacion" field
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findOneBy(array('vendedor' => NULL), array('caja.fecha_creacion' => 'DESC'));
According to the doc, you can't pass a second parameter to the findOnyBy function.
But you can try to cheat by using the findBy methods and the position of this array :
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findNextLibreta(NULL, $actualPosicion);
...
And in your repository :
public function findNextLibreta($vendedor, $posicion) {
$qb = $this->createQueryBuilder('l');
$qb->leftJoin(l.caja, 'c')
->where('l.vendedor = :vendedor')
->setParameter(':type', $type)
->orderBy('c.fecha_creacion', 'DESC');
$results = $qb->getQuery()->getResult();
return $results[$posicion];
}
Thanks to #JulienBourdic I changed a little his proposal but him basically gave me the answer. The code is:
$posicion = 0;
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findByNextLibreta($posicion);
Then in LibretaRepository.php
public function findByNextLibreta($posicion) {
$qb = $this->createQueryBuilder('l');
$qb->leftJoin('l.caja', 'c')
->where('l.vendedor is NULL')
->orderBy('c.fecha_creacion', 'DESC');
$results = $qb->getQuery()->getResult();
return $results[$posicion];
}
It differs a little cuz didn't know how to pass the NULL value Julien was proposing so I used l.vendedor is NULL burned in the code.
I have an Article and Subcategory entities, I want, using Doctrine DQL, select all the subcategories that have 1 or more articles, I don't want to select empty Subcategories .. How can I do that in one query
Here are my objects:
Article
<?php
namespace Evr\ArticleBundle\Entity;
use Evr\HomeBundle\Entity\ImageThumbnail;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Article
*
* #ORM\Table(name="ev_article")
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Article{
/**
* #var integer
*
* #ORM\Column(name="article_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #ORM\ManyToOne(targetEntity="Evr\HomeBundle\Entity\Subcategory",inversedBy="articles")
* #ORM\JoinColumn(name="subcategory_id",referencedColumnName="subcategory_id")
*/
private $subcategory;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var integer
*
* #ORM\Column(name="type", type="integer")
*/
private $type;
/**
* #var text
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var text
*
* #ORM\Column(name="exclusive_content", type="text")
*/
private $exclusive_content;
/**
* #var \DateTime
*
* #ORM\Column(name="creation_date", type="date")
*/
private $creation_date;
/**
* #var integer
*
* #ORM\Column(name="views", type="integer" , nullable=true)
*/
private $views;
/**
* #var integer
*
* #ORM\Column(name="votes", type="integer", nullable=true)
*/
private $votes;
/**
* #var string
*
* #ORM\Column(name="photo", type="string", length=255, nullable=true)
*/
protected $photo;
/**
* Image file
*
* #var File
*
* #Assert\File(
* maxSize = "5M",
* mimeTypes = {"image/jpeg", "image/gif", "image/png", "image/tiff"},
* maxSizeMessage = "The maxmimum allowed file size is 5MB.",
* mimeTypesMessage = "Only the filetypes image are allowed."
* )
*/
protected $file;
private $temp;
public function getAbsolutePath() {
return (null === $this->photo) ? null : $this->getUploadRootDir() . '/' . $this->photo;
}
public function getWebPath() {
return (null === $this->photo) ? null : $this->getUploadDir() . '/' . $this->photo;
}
protected function getUploadRootDir() {
return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}
public function getUploadDir() {
return 'uploads/documents/';
}
public function getThumbPath() {
return 'uploads/documents/thumbs/';
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set subcategory
*
* #param integer $subcategory
* #return Article
*/
public function setSubcategory($subcategory) {
$this->subcategory = $subcategory;
return $this;
}
/**
* Get subcategory
*
* #return integer
*/
public function getSubcategory() {
return $this->subcategory;
}
/**
* Set title
*
* #param string $title
* #return Article
*/
public function setTitle($title) {
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle() {
return $this->title;
}
/**
* Set type
*
* #param integer $type
* #return Article
*/
public function setType($type) {
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return integer
*/
public function getType() {
return $this->type;
}
/**
* Set content
*
* #param text $content
* #return Article
*/
public function setContent($content) {
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return text
*/
public function getContent() {
return $this->content;
}
/**
* Set exclusive_content
*
* #param text $exclusiveContent
* #return Article
*/
public function setExclusiveContent($exclusiveContent) {
$this->exclusive_content = $exclusiveContent;
return $this;
}
/**
* Get exclusive_content
*
* #return text
*/
public function getExclusiveContent() {
return $this->exclusive_content;
}
/**
* Set creation_date
*
* #param DateTime $creationDate
* #return Article
*/
public function setCreationDate($creation_date) {
$this->creation_date = $creation_date;
return $this;
}
/**
* Get creation_date
*
* #return DateTime
*/
public function getCreationDate() {
return $this->creation_date;
}
/**
* Set views
*
* #param integer $views
* #return Article
*/
public function setViews($views = 0) {
$this->views = $views;
return $this;
}
/**
* Get views
*
* #return integer
*/
public function getViews() {
return $this->views;
}
/**
* Set votes
*
* #param integer $votes
* #return Article
*/
public function setVotes($votes) {
$this->votes = $votes;
return $this;
}
/**
* Get votes
*
* #return integer
*/
public function getVotes() {
return $this->votes;
}
/**
* Set photo
*
* #param string $photo
* #return Article
*/
public function setPhoto($photo) {
$this->photo = $photo;
return $this;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto() {
return $this->photo;
}
/**
* Set file
*
* #param UploadedFile $file
* #return Article
*/
public function setFile(UploadedFile $file = null) {
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return UploadedFile
*/
public function getFile() {
return $this->file;
}
/**
* Called before saving the entity
*
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload() {
if (null !== $this->file) {
$filename = sha1(uniqid(mt_rand(), true));
$this->photo = $filename . '.' . $this->file->guessExtension();
}
}
/**
* Called after entity persistence
*
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload() {
if (null === $this->file) {
return;
}
$this->file->move(
$this->getUploadRootDir(), $this->photo
);
$this->file = null;
}
/**
* Called before entity removal
*
* #ORM\PostRemove()
*/
public function removeUpload() {
if ($file = $this->getAbsolutePath()) {
if (file_exists($file)) {
unlink($file);
}
}
}
public function updateUploadedFile($file) {
$this->removeUpload();
$this->file = $file;
$this->preUpload();
$this->upload();
}
}
And Subcategory
<?php
namespace Evr\HomeBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Subcategory
*
* #ORM\Table(name="ev_subcategory")
* #ORM\Entity
*/
class Subcategory
{
/**
* #var integer
*
* #ORM\Column(name="subcategory_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #ORM\ManyToOne(targetEntity="Category",inversedBy="subcategories")
* #ORM\JoinColumn(name="category_id",referencedColumnName="category_id")
*/
private $category;
/**
* #var string
*
* #ORM\Column(name="subcategory", type="string", length=255)
*/
private $subcategory;
/**
* #ORM\OneToMany(targetEntity="Evr\ArticleBundle\Entity\Article", mappedBy="subcategory")
*/
protected $articles;
/**
* #ORM\OneToMany(targetEntity="Evr\CourseBundle\Entity\Course", mappedBy="subcategory")
*/
protected $courses;
public function __construct(){
$this->articles=new ArrayCollection();
$this->courses=new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set category
*
* #param integer $category
* #return Subcategory
*/
public function setCategory($category) {
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return integer
*/
public function getCategory() {
return $this->category;
}
/**
* Set subcategory
*
* #param string $subcategory
* #return Subcategory
*/
public function setSubcategory($subcategory)
{
$this->subcategory = $subcategory;
return $this;
}
/**
* Get subcategory
*
* #return string
*/
public function getSubcategory()
{
return $this->subcategory;
}
/**
* Get articles
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getArticles()
{
return $this->articles;
}
}