I have such doctrine entities:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity(repositoryClass="App\Repository\Page")
* #Table(name="page")
*/
class Page
{
/**
* #Id #Column(type="integer", name="p_id")
* #GeneratedValue
*/
private $p_id;
/** #Column(type="string", name="p_title") */
private $p_title;
/** #Column(type="datetime", name="p_created") */
private $p_created_at;
/** #Column(type="datetime", name="p_updated_at") */
private $p_updated_at;
/** #Column(type="text", name="p_abstract") */
private $p_abstract;
/** #Column(type="text", name="p_fulltext", nullable=false) */
private $p_fulltext;
/** #Column(type="string", name="p_author", nullable=true) */
private $p_author;
/** #Column(type="string", name="p_url",nullable=true) */
private $p_url;
/** #Column(type="string", name="p_meta_title",nullable=true) */
private $p_meta_title;
/** #Column(type="string", name="p_meta_keywords",nullable=true) */
private $p_meta_keywords;
/** #Column(type="string", name="p_meta_description",nullable=true) */
private $p_meta_description;
/** #Column(type="string", name="p_status") */
private $p_status;
/**
* #ManyToOne(targetEntity="User", inversedBy="pages")
* #JoinColumn(name="p_u_id", referencedColumnName="u_id")
*/
private $user;
/**
* #OneToMany(targetEntity="App\Entity\Page\Media", mappedBy="pages")
* #var \Doctrine\Common\Collections\Collection
*/
protected $pageMedia;
/**
* #OneToMany(targetEntity="App\Entity\Page\Basket", mappedBy="baskets")
* #var \Doctrine\Common\Collections\Collection
*/
protected $pageBasket;
public function __construct()
{
$this->pageMedia = new App\Entity\Page\Media();
$this->medias = new ArrayCollection();
}
public function __get($property)
{
return $this->property;
}
public function __set($property,$value)
{
$this->$property = $value;
}
public function setUser(user $user)
{
$this->user = $user;
}
public function setMedia(media $media)
{
$this->pageMedia->setPageAndMedia($this,$media);
}
/**
* Set Page Values
* #var array $values
*/
public function setPageProperties(array $values)
{
$this->p_updated_at = new \DateTime("now");
$this->p_title = $values['p_title'];
$this->p_abstract = $values['p_abstract'];
$this->p_meta_title = $values['p_meta_title'];
$this->p_meta_keywords = $values['p_meta_keywords'];
$this->p_meta_description = $values['p_meta_description'];
$this->p_url = $values['p_url'];
$this->p_fulltext = $values['p_abstract'];
$this->p_author = '';
$this->p_status = 1;
}
}
?>
<?php
namespace App\Entity\Page;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="page_basket")
*/
class Basket
{
/**
* #Id #Column(type="integer", name="pb_id")
* #GeneratedValue
*/
private $pb_id;
/**
* #ManyToOne(targetEntity="App\Entity\Page")
* #JoinColumn(name="pb_p_id", referencedColumnName="p_id")
*/
private $pages;
/**
* #ManyToOne(targetEntity="App\Entity\Basket",inversedBy="pageBasket")
* #JoinColumn(name="pb_b_id", referencedColumnName="b_id")
*/
private $baskets;
public function __construct()
{
$this->baskets = new ArrayCollection();
$this->pages = new ArrayCollection();
}
public function __get($property)
{
return $this->property;
}
public function __set($property,$value)
{
$this->$property = $value;
}
/**
*
*/
public function setPageAnBasket(page $page,basket $basket)
{
$this->pages[] = $page;
$this->baskets[] = $basket;
}
}
?>
And method in repository:
<?php
namespace App\Repository;
use Doctrine\ORM\EntityRepository;
class Page extends EntityRepository
{
/**
* Find pages by basket Id
* #var int $basketId
* #return array $pages[]
*/
public function findPagesByBasket($basketId)
{
$dql = $this->_em->createQueryBuilder();
$dql->select('u')
->from('App\Entity\Page', 'p')
->leftJoin('p.App\Entity\Page\Basket','pb_b_id = p_id')
->andWhere('pb_b_id = :basketId')
->setParameter('basketId', $basketId);
return $dql->getQuery()->getArrayResult();
}
}
But when I ry to run dql all I'm getting:
string '[Semantical Error] line 0, col 67 near 'pb_b_id = p_id': Error: Class App\Entity\Page has no association named App\Entity\Page\Basket'
What I'm doing wrong because I don't want to use many to many relation because I wanna have additional fields in join table.
I needed a good excuse to make myself a simple test case so here it is.
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity()
* #Table(name="page")
*/
class Page
{
/**
* #Id #Column(type="integer", name="p_id")
* #GeneratedValue
*/
private $id;
/**
* #OneToMany(targetEntity="Entity\PageBasket", mappedBy="page")
*/
protected $pageBaskets;
public function __construct()
{
$this->pageBaskets = new ArrayCollection();
}
public function getId() { return $this->id; }
public function getPageBaskets() { return $this->pageBaskets; }
}
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="page_basket")
*/
class PageBasket
{
/**
* #Id #Column(type="integer", name="pb_id")
* #GeneratedValue
*/
private $id;
/**
* #ManyToOne(targetEntity="Entity\Page")
* #JoinColumn(name="page_id", referencedColumnName="p_id")
*/
private $page;
public function setPage($page)
{
$this->page = $page;
}
public function getId() { return $this->id; }
}
And a working test query
protected function testQuery()
{
$basketId = 1;
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->addSelect('page');
$qb->addSelect('pageBasket');
$qb->from('\Entity\Page','page');
$qb->leftJoin('page.pageBaskets','pageBasket');
$qb->andWhere($qb->expr()->in('pageBasket.id',$basketId));
$query = $qb->getQuery();
$results = $query->getResult();
$page = $results[0];
$pageBaskets = $page->getPageBaskets();
$pageBasket = $pageBaskets[0];
echo 'Result Count ' . count($results) . "\n";
echo 'Page ID ' . $page->getId() . "\n";
echo 'Page Basket ID ' . $pageBasket->getId() . "\n";
echo $query->getSQL() . "\n";
}
The generated sql look like:
SELECT p0_.p_id AS p_id0, p1_.pb_id AS pb_id1, p1_.page_id AS page_id2
FROM page p0_
LEFT JOIN page_basket p1_ ON p0_.p_id = p1_.page_id
WHERE p1_.pb_id IN (1)
Related
I'm using Doctrine in my Symfony3 project. I'm using the entity manager to get my data from the database but I have an unexpected error which seems to be generated by doctrine.
An exception has been thrown during the rendering of a template ("An exception occurred while executing 'SELECT t0.id AS id_1, t0.date AS date_2, t0.comment AS comment_3, t0.viewed AS viewed_4, t0.error_count AS error_count_5, t0.of_id AS of_id_6, t0.checkpoint_id AS checkpoint_id_7, t8.id AS id_9, t8.name AS name_10, t8.description AS description_11, t8.deleted_at AS deleted_at_12, t8.factory_id AS factory_id_13, t0.operateur_id AS operateur_id_15, t0.factory_id AS factory_id_16 FROM app_check_set t0 LEFT JOIN app_checkpoint t8 ON t0.checkpoint_id = t14.id AND ((t14.deleted_at IS NULL)) WHERE t0.factory_id = ? ORDER BY t0.date DESC LIMIT 5' with params [3]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 't14.id' in 'on clause'").
As I'm not creating the query myself, i would like to know where is this error coming from ? Is it related with my entity configuration ?
The problem is when I want to get my entities Checkset :
public function notificationsAction(Request $request){
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
return $this->render('AppBundle:Home:notifications.html.twig', array(
'notifications' => $em->getRepository('AppBundle:CheckSet')->findBy(array('factory' => $user->getFactory()->getId()), array('date' => 'desc'), 5),
'count' => count($em->getRepository('AppBundle:CheckSet')->findBy(array('factory' => $user->getFactory()->getId(), 'viewed' => false)))
));
}
My entities are like this :
CheckSet:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use UserBundle\Entity\User;
use Doctrine\Common\Collections\ArrayCollection;
/**
* CheckSet
*
* #ORM\Table(name="app_check_set")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CheckSetRepository")
*/
class CheckSet
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #var string
* #ORM\Column(name="comment", type="text", nullable=true)
*/
private $comment;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElementResult", mappedBy="checkSet", cascade={"persist"})
*/
private $checkElementResult;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElementResultObservation", mappedBy="checkSet", cascade={"persist"})
*/
private $observations;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Of", inversedBy="checkSet")
* #ORM\JoinColumn(name="of_id", referencedColumnName="id")
*/
private $of;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\CheckPoint", inversedBy="checkSet", fetch="EAGER")
* #ORM\JoinColumn(name="checkpoint_id", referencedColumnName="id")
*/
private $checkPoint;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="checkSet")
* #ORM\JoinColumn(name="operateur_id", referencedColumnName="id")
*/
private $operateur;
/**
* #ORM\Column(type="boolean", nullable=false, options={"default" : false})
*/
protected $viewed = FALSE;
/**
* #ORM\Column(type="integer", nullable=false)
*/
protected $errorCount;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Factory", inversedBy="checkSet")
* #ORM\JoinColumn(name="factory_id", referencedColumnName="id")
*/
private $factory;
public function __construct($gamme = null, $of = null, $user = null){
$this->checkElementResult = new ArrayCollection();
$this->observations = new ArrayCollection();
$this->date = new \DateTime();
$this->errorCount = 0;
if ($gamme != null){
$this->checkPoint = $gamme;
}
if ($of != null){
$this->of = $of;
}
if ($user != null){
$this->operateur = $user;
$this->factory = $user->getFactory();
}
}
public function getId(){
return $this->id;
}
public function setDate($date){
$this->date = $date;
return $this;
}
public function getDate(){
return $this->date;
}
public function setErrorCount($errorCount){
$this->errorCount = $errorCount;
return $this;
}
public function getErrorCount(){
return $this->errorCount;
}
public function setComment($comment){
$this->comment = $comment;
return $this;
}
public function getComment(){
return $this->comment;
}
public function setOperateur(User $operateur){
$this->operateur = $operateur;
return $this;
}
public function getOperateur(){
return $this->operateur;
}
public function setOf(Of $of){
$this->of = $of;
return $this;
}
public function getOf(){
return $this->of;
}
public function setFactory(Factory $factory){
$this->factory = $factory;
return $this;
}
public function getFactory(){
return $this->factory;
}
public function setCheckPoint(Checkpoint $checkPoint){
$this->checkPoint = $checkPoint;
return $this;
}
public function getCheckPoint(){
return $this->checkPoint;
}
/*------------------------------------------------------------------------CheckElementResult*/
public function addCheckElementResult(CheckElementResult $cke){
$this->checkElementResult[] = $cke;
$cke->setCheckSet($this);
return $this;
}
public function removeCheckElementResult(CheckElementResult $cke){
$this->checkElementResult->removeElement($cke);
}
public function getcheckElementResult(){
return $this->checkElementResult;
}
/*------------------------------------------------------------------------observations*/
public function addObservations(CheckElementResultObservation $cke){
$this->observations[] = $cke;
$cke->setCheckSet($this);
return $this;
}
public function removeObservations(CheckElementResultObservation $cke){
$this->observations->removeElement($cke);
}
public function getObservations(){
return $this->observations;
}
/*-------------------------------------------------------VIEWED*/
public function setViewed($viewed){
$this->viewed = $viewed;
return $this;
}
public function getViewed(){
return $this->viewed;
}
public function isViewed(){
return $this->viewed;
}
public function countErrors(){
$err = 0;
foreach ($this->checkElementResult as $key => $ckeR) {
foreach ($ckeR->getCheckElement()->getAlert() as $key => $alert) {
if( $alert->getOperator() == "==" && $ckeR->getValue() == $alert->getValue()){
$err++;
}elseif ( $alert->getOperator() == "!=" && $ckeR->getValue() != $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == "<" && $ckeR->getValue() < $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == ">" && $ckeR->getValue() > $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == "<=" && $ckeR->getValue() <= $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == ">=" && $ckeR->getValue() >= $alert->getValue()) {
$err++;
}
}
}
return $err;
}
public function __toString(){
return $this->of->getName().' '.$this->checkPoint->getName();
}
}
CheckPoint:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Checkpoint
*
* #ORM\Table(name="app_checkpoint")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CheckpointRepository")
* #Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
*/
class Checkpoint
{
/**
* #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)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElement", mappedBy="checkpoint",cascade={"persist"}, orphanRemoval=true)
* #ORM\OrderBy({"position" = "ASC"})
*/
private $checkElements;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Operation", mappedBy="checkpoint",cascade={"persist"})
*/
private $operation;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Factory", inversedBy="checkpoints")
* #ORM\JoinColumn(name="factory_id", referencedColumnName="id")
*/
private $factory;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckSet", mappedBy="checkPoint")
*/
private $checkSet;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckListOf", mappedBy="checkPoint")
*/
private $checkListOf;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $deletedAt;
public function __construct(){
$this->checkElements = new ArrayCollection();
}
public function getId(){
return $this->id;
}
public function setName($name){
$this->name = $name;
return $this;
}
public function getName(){
return $this->name;
}
public function setDescription($description){
$this->description = $description;
return $this;
}
public function getDescription(){
return $this->description;
}
public function getFactory(){
return $this->factory;
}
public function setFactory($factory){
$this->factory = $factory;
}
/*------------------------------------------------------------------------Checkelements*/
public function addCheckElement(CheckElement $cke){
$this->checkElements[] = $cke;
$cke->setCheckpoint($this);
return $this;
}
public function removeCheckElement(CheckElement $cke){
$this->checkElements->removeElement($cke);
}
public function getCheckElements(){
return $this->checkElements;
}
public function __toString(){
return $this->name;
}
}
The problem could be because of the soft delete but I'm not sure ... The controller I'm calling (notificationsAction) is embed in my header.
In this page (the notifications area) I want to display objects which may have been deleted. The problem happend when the checkpoint I want to display (the one related to the Checkset objects) has been deleted
<!-- NOTIFICATIONS -->
{{ render(controller('AppBundle:Home:notifications', {'request': app.request})) }}
Your issue is actually the same as here.
Your class name is Checkpoint and I guess the file is named checkpoint.php (note that if you are developing on windows, the filename is case-insensitive). All are lowercase.
In your CheckSet class you have
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\CheckPoint", inversedBy="checkSet", fetch="EAGER")
* #ORM\JoinColumn(name="checkpoint_id", referencedColumnName="id")
*/
private $checkPoint;
The targetEntity is to "AppBundle\Entity\CheckPoint" with capital P.
The issue is that because of this, doctrine create a new alias for a new table (the php comparison is case sensitive github link).
To solve this, change your class name and file to CheckPoint with capital P:
class CheckPoint
{
When I try to do this
$forgottenLoginRepo = $this->doctrine->em->getRepository('models\ForgottenLogin');
$forgottenLogin = $forgottenLoginRepo->findOneBy(
array(
'passwordKey' => $key
)
);
I get this error
Entity 'models\ForgottenLogin' has a composite identifier but uses an
ID generator other than manually assigning (Identity, Sequence). This
is not supported.
My model is
<?php
/**
* Created by PhpStorm.
* User: Manisha.DeSilva
* Date: 06/07/2017
* Time: 13:03
*/
namespace models;
/**
* #Entity
* #Table(name="park_forgotten_login")
*
*/
class ForgottenLogin
{
/**
* #Id
* #Column(name="id", type="integer", nullable=false)
* #GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
}
/**
* #Id
* #ManyToOne(targetEntity="Customer")
* #JoinColumn(name="customer_id", referencedColumnName="id")
*/
private $customer;
public function getCustomer()
{
return $this->customer;
}
public function setCustomer($value)
{
$this->customer = $value;
}
/**
* #Column(name="password_Key", type="string", nullable=false)
*/
private $passwordKey;
public function getPasswordKey()
{
return $this->passwordKey;
}
public function setPasswordKey($value)
{
$this->passwordKey = $value;
}
/**
* #Column(name="expiry", type="datetime", nullable=false)
*/
private $expiry;
public function getExpiry()
{
return $this->expiry;
}
public function setExpiry($value)
{
$this->expiry = $value;
}
private $forgottenFlag;
public function getForgottenFlag()
{
return $this->forgottenFlag;
}
public function setForgottenFlag($value)
{
$this->forgottenFlag = $value;
}
}
I have three database tables. user, meeting, group. The meetings and group table are manytomany associations from the user table. So I can do user->getmeetings(), or user->getgroups().
I want to get just the next meeting comping up for the user, and I don't know how to achieve this. Whether by SQL Query or simply in the controller. Here is what I have done so far.
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
I have added a time_diff field in the new array to calculate the time from now to the meeting time. All I need to do now is select the smallest one.How can I do this? Thank you.
UPDATE - Below is my User Repository
namespace AppBundle\Repository;
use AppBundle\Entity\User;
use AppBundle\Entity\Meeting;
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\Criteria;
class UserRepository extends EntityRepository
{
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
$this->getMeetings()->matching($criteria);
}
}
Below is my User Entity
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #ORM\Table(name="user")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $first_name;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $last_name;
/**
* #ORM\Column(type="string", nullable=false, unique=true)
*/
private $email_address;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $phone_number;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $password;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_login;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $reset_password;
/**
* #ORM\ManyToMany(targetEntity="Meeting", inversedBy="users")
*/
private $meetings;
/**
* #ORM\ManyToMany(targetEntity="Group", inversedBy="users")
*/
private $groups;
public function __construct()
{
$this->groups = new arrayCollection();
$this->meetings = new arrayCollection();
}
/**
* #return mixed
*/
public function getFirstName()
{
return $this->first_name;
}
/**
* #param mixed $first_name
*/
public function setFirstName($first_name)
{
$this->first_name = $first_name;
}
/**
* #return mixed
*/
public function getLastName()
{
return $this->last_name;
}
/**
* #param mixed $last_name
*/
public function setLastName($last_name)
{
$this->last_name = $last_name;
}
/**
* #return mixed
*/
public function getEmailAddress()
{
return $this->email_address;
}
/**
* #param mixed $email_address
*/
public function setEmailAddress($email_address)
{
$this->email_address = $email_address;
}
/**
* #return mixed
*/
public function getPhoneNumber()
{
return $this->phone_number;
}
/**
* #param mixed $phone_number
*/
public function setPhoneNumber($phone_number)
{
$this->phone_number = $phone_number;
}
/**
* #return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* #param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return mixed
*/
public function getLastLogin()
{
return $this->last_login;
}
/**
* #param mixed $last_login
*/
public function setLastLogin($last_login)
{
$this->last_login = $last_login;
}
/**
* #return mixed
*/
public function getResetPassword()
{
return $this->reset_password;
}
/**
* #param mixed $reset_password
*/
public function setResetPassword($reset_password)
{
$this->reset_password = $reset_password;
}
/**
* #return arrayCollection|Meeting[]
*/
public function getMeetings()
{
return $this->meetings;
}
/**
* #return ArrayCollection|Group[]
*/
public function getGroups()
{
return $this->groups;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
}
below is my HomeControlller.php
class HomeController extends Controller
{
/**
* #Route("/home", name="home_show")
*/
public function showAction()
{
$em = $this->getDoctrine()->getManager();
//logged in user
$id = 1;
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
$groups = $em->getRepository('AppBundle\Entity\Group')
->findAll();
return $this->render('home/show.html.twig', [
'loggedInUser' => $loggedInUser,
'groups' => $groups,
]);
}
}
You can add a method in your UserEntity with a matching criteria on meeting collection
namespace AppBundle\Entity;
use Doctrine\Common\Collections\Criteria;
....
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
return $this->getMeetings()->matching($criteria);
}
see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/working-with-associations.html
Here is my Insert Query, how can I tell that, created_at(current time-stamp), is_active(default 1) set in the mysql db structure needs to be taken.
When I omit the $question->setCreatedAt($this->createdAt); in the insert operation it shows me an Integrity constraint violation, do you know what is the issue?
In the Questions table:
question:
id
question
created_by
created_at
modified_by
modified_at
is_Active
Entity:
<?php
namespace Library\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Base class for all the Entities
* This class maps id, active, created and modified columns
*
* #author
*/
/**
* #ORM\MappedSuperclass
*/
class BaseEntity {
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(name="id", type="integer")
* #var integer
*/
protected $id;
/**
* #ORM\Column(name="is_active", type="boolean")
* #var boolean
*/
protected $active;
/**
* #ORM\Column(name="created_at", type="datetime")
* #var datetime
*/
protected $createdAt;
/**
* #ORM\Column(name="created_by", type="integer", nullable=true)
* #var integer
*/
protected $createdBy;
/**
* #ORM\Column(name="modified_at", type="datetime")
* #var datetime
*/
protected $modifiedAt;
/**
* #ORM\Column(name="modified_by", type="integer")
* #var integer
*/
protected $modifiedBy;
public function getId() {
return $this->id;
}
public function getActive() {
return $this->active;
}
public function getCreatedAt() {
return $this->createdAt;
}
public function getCreatedBy() {
return $this->createdBy;
}
public function getModifiedAt() {
return $this->modifiedAt;
}
public function getModifiedBy() {
return $this->modifiedBy;
}
public function setId($id) {
$this->id = $id;
}
public function setActive($active) {
$this->active = $active;
}
public function setCreatedAt($createdAt) {
$this->createdAt = $createdAt;
}
public function setCreatedBy($createdBy) {
$this->createdBy = $createdBy;
}
public function setModifiedAt($modifiedAt) {
$this->modifiedAt = $modifiedAt;
}
public function setModifiedBy($modifiedBy) {
$this->modifiedBy = $modifiedBy;
}
}
This is my Question Entity:
<?php
namespace Survey\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Library\Entity\BaseEntity;
use Survey\Entity\Survey;
/**
* Description of Survey Questions
*
* #author Mubarak
*/
/**
* #ORM\Entity
* #ORM\Table(name="survey_questions")
*/
class Question extends BaseEntity{
/**
* #ORM\Column(name="question", type="string")
* #var string
*/
protected $question;
/**
* #ORM\ManyToOne(targetEntity="Survey\Entity\Survey", inversedBy="questions")
* #ORM\JoinColumn(name="survey_id", referencedColumnName="id")
*/
private $surveys;
public function getQuestion() {
return $this->question;
}
public function setQuestion($question) {
$this->question = $question;
}
public function getSurveys() {
return $this->surveys;
}
// public function setSurveys(ArrayCollection $survey) {
public function setSurveys(Survey $surveys = null) {
$this->surveys = $surveys;
}
// public function __toString() {
// return __CLASS__ . ": [id: {$this->id}, name: {$this->name}]";
// }
}
Here is my insert Operation:
public function insertQuestion($userId, $survey, $questionArr) {
try{
$question = new Question();
$question->setQuestion($questionArr['question']);
$question->setSurveys($survey);
$question->setActive(1);
$question->setCreatedBy($userId);
$question->setCreatedAt($this->createdAt);
$question->setModifiedBy($userId);
$question->setModifiedAt($this->modifiedAt);
$this->entityManager->persist($question);
$this->entityManager->flush();
return $question;
}catch(Exception $ex){
throw new Exception("Couldnt insert the question");
}
}
This is Ok, its working properly, but i dont want to insert the Created_at, modified_at
public function insertQuestion($userId, $survey, $questionArr) {
try{
$question = new Question();
$question->setQuestion($questionArr['question']);
$question->setSurveys($survey);
$question->setActive(1);
$question->setCreatedBy($userId);
$question->setModifiedBy($userId);
$this->entityManager->persist($question);
$this->entityManager->flush();
return $question;
}catch(Exception $ex){
throw new Exception("Couldnt insert the question");
}
}
If you want to set default values it is best to set them in your object model where possible.
/**
* #ORM\Column(name="is_active", type="boolean")
* #var boolean
*/
protected $active = true;
For time-stamps though it is a bit of a different story...
I would suggest to take a look at the Gedmo doctrine extensions library which includes solutions for createdAt and other common columns for your model. No need to reinvent the wheel... .
I am having troubles with user authorization.
This is my User
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
* #var int id
*/
protected $id;
/**
* #ORM\Column(type="string", length=25)
*
* #var string username
*/
protected $username;
/**
* #ORM\Column(type="string", length=25)
*
* #var string password
*/
protected $password;
/**
* #ORM\Column(type="string", length=25)
*
* #var string firstName
*/
protected $firstName;
/**
* #ORM\Column(type="string", length=25)
*
* #var string lastName
*/
protected $lastName;
/**
* #ORM\Column(type="string", length=25)
*
* #var string email
*/
protected $email;
/**
* #ORM\Column(type="string", length=255)
*
* #var string salt
*/
protected $salt;
/**
* #ORM\ManyToMany(targetEntity="Role")
* #ORM\JoinTable(name="user_role",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*
* #var ArrayCollection $userRoles
*/
protected $userRoles;
public function __construct()
{
$this->posts = new ArrayCollection();
$this->userRoles = new ArrayCollection();
$this->createdAt = new \DateTime();
}
public function getId()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function getPassword()
{
return $this->password;
}
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
public function getEmail()
{
return $this->email;
}
public function getSalt()
{
return $this->salt;
}
public function getUserRoles()
{
return $this->userRoles;
}
public function getRoles()
{
return $this->getUserRoles()->toArray();
}
public function setUsername($username)
{
$this->username = $username;
}
public function setPassword($password)
{
$this->password = $password;
}
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
public function setEmail($email)
{
$this->email = $email;
}
public function setSalt($value)
{
$this->salt = $value;
}
public function eraseCredentials()
{
}
public function equals(UserInterface $user)
{
return md5($this->getUsername()) == md5($user->getUsername());
}
}
And this is my Role
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="role")
*/
class Role implements RoleInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
* #var integer $id
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #var string $name
*/
protected $name;
/**
* #ORM\Column(type="datetime", name="created_at")
*
* #var DateTime $createdAt
*/
protected $createdAt;
/**
* Геттер для id.
*
* #return integer The id.
*/
public function getId()
{
return $this->id;
}
/**
* Геттер для названия роли.
*
* #return string The name.
*/
public function getName()
{
return $this->name;
}
/**
* Сеттер для названия роли.
*
* #param string $value The name.
*/
public function setName($value)
{
$this->name = $value;
}
/**
* Геттер для даты создания роли.
*
* #return DateTime A DateTime object.
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Конструктор класса
*/
public function __construct()
{
$this->createdAt = new \DateTime();
}
/**
* Реализация метода, требуемого интерфейсом RoleInterface.
*
* #return string The role.
*/
public function getRole()
{
return $this->getName();
}
}
RoleHierarchy.php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Role;
/**
* RoleHierarchy defines a role hierarchy.
*
* #author Fabien Potencier <fabien#symfony.com>
*/
class RoleHierarchy implements RoleHierarchyInterface
{
private $hierarchy;
protected $map;
/**
* Constructor.
*
* #param array $hierarchy An array defining the hierarchy
*/
public function __construct(array $hierarchy)
{
$this->hierarchy = $hierarchy;
$this->buildRoleMap();
}
/**
* {#inheritdoc}
*/
public function getReachableRoles(array $roles)
{
$reachableRoles = $roles;
foreach ($roles as $role) {
if (!isset($this->map[$role->getRole()])) {
continue;
}
foreach ($this->map[$role->getRole()] as $r) {
$reachableRoles[] = new Role($r);
}
}
return $reachableRoles;
}
protected function buildRoleMap()
{
$this->map = array();
foreach ($this->hierarchy as $main => $roles) {
$this->map[$main] = $roles;
$visited = array();
$additionalRoles = $roles;
while ($role = array_shift($additionalRoles)) {
if (!isset($this->hierarchy[$role])) {
continue;
}
$visited[] = $role;
$this->map[$main] = array_unique(array_merge($this->map[$main], $this->hierarchy[$role]));
$additionalRoles = array_merge($additionalRoles, array_diff($this->hierarchy[$role], $visited));
}
}
}
}
I am getting next error - FatalErrorException in RoleHierarchy.php line 43: Error: Call to a member function getRole() on string
How should i solve the problem?