I'm trying to create an website in Symfony in which I have a database with Movies. This how it looks like:
/**
* Game entity.
*/
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Movie.
*
* #ORM\Table(name="movies")
* #ORM\Entity(repositoryClass="AppBundle\Repository\Movie")
*/
class Movie
{
/**
* Id.
*
* #ORM\Id
* #ORM\Column(
* type="integer",
* nullable=false,
* options={
* "unsigned" = true
* }
* )
* #ORM\GeneratedValue(strategy="IDENTITY")
*
* #var integer $id
*/
private $id;
/**
* Title.
*
* #ORM\Column(
* name="title",
* type="string",
* length=255,
* nullable=false
* )
*
* #var string $title
*/
private $title;
/**
* Notes.
*
* #ORM\Column(
* name="notes",
* type="text",
* nullable=true
* )
*
* #var string $notes
*/
private $notes;
/**
* Genres array
*
* #ORM\ManyToOne(targetEntity="Genre")
* #ORM\JoinColumn(name="genre_id", referencedColumnName="id")
* )
*
* #var \Doctrine\Common\Collections\ArrayCollection $genres
*/
protected $genres;
/**
* Constructor.
*/
public function __construct()
{
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id.
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param integer $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Set title.
*
* #param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Get title.
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set notes.
*
* #param string $notes
*/
public function setNotes($notes)
{
$this->notes = $notes;
}
/**
* Get notes.
*
* #return string
*/
public function getNotes()
{
return $this->notes;
}
/**
* Add genres
*
* #param \AppBundle\Entity\Genre $genres
* #return Movie
*/
public function addGenre(\AppBundle\Entity\Genre $genres)
{
$this->genres[] = $genres;
return $this;
}
/**
* Set genres
*
* #param \AppBundle\Entity\Genre $genres
* #return Movie
*/
public function setGenres(\AppBundle\Entity\Genre $genres = null)
{
$this->genres = $genres;
return $this;
}
/**
* Get genres
*
* #return \AppBundle\Entity\Genre
*/
public function getGenres()
{
return $this->genres;
}
}
And each Movie has a Genre:
/**
* Genere entity.
*
*/
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Genere.
*
* #ORM\Table(name="genere")
* #ORM\Entity(repositoryClass="AppBundle\Repository\Genere")
*/
class Genere
{
/**
* Id.
*
* #ORM\Id
* #ORM\Column(
* type="integer",
* nullable=false,
* options={
* "unsigned" = true
* }
* )
* #ORM\GeneratedValue(strategy="IDENTITY")
*
* #var integer $id
*/
private $id;
/**
* Name.
*
* #ORM\Column(
* name="name",
* type="string",
* length=128,
* nullable=false
* )
*
* #var string $name
*/
private $name;
/**
* Get Id.
*
* #return integer Result
*/
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
/**
* Set name.
*
* #param string $name Name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name.
*
* #return string Name
*/
public function getName()
{
return $this->name;
}
Now, my question is: how can I show a genre in movies list? I know how to make a list of movies, but no idea what to use to show genres.
My MovieController currently looks like this:
/**
* List action.
*
* #Route("/movie-list", name="movies-list")
* #Route("/movies-list/")
*
* #throws NotFoundHttpException
* #return Response A Response instance
*/
public function listAction()
{
$movies = $this->findByStatId(2);
if (!$movies) {
throw new NotFoundHttpException('Movies not found!');
}
return $this->templating->renderResponse(
'AppBundle:Movie:index.html.twig',
array('movies' => $movies)
);
}
What should I add to be able to show genres? Where? Any advises would be welcome.
You already have genres along with $movies variable. You just have to call access genres like this:
{% for genre in movies.genres %}
{# Access each genre variable here #}
{% endfor %}
movies is a object passed to twig file and it has property genres to access related genres in it.
To access genres on controller:
<?php
$genres=$movies->getGenres();
// loop through $genres.
?>
getGenres() will return collection of genres.
You have a mistake in your Genre class. At least in your example, you call it Genere instead of Genre. Second, if a movie should have more than one genre then you should make a many-to-many association, as multiple movies can have the same genre. If a movie can only have one genre, then you have to switch the owning side with Genre (Movie should have Genre (singular), Genre should have Movies (plural))
Related
I have 2 entities Cars and Parts and I want to be able to create new Car with multiple parts. For this reason I made this form in CarsType
$builder->
add('make')->
add('model')->
add('travelledDistance')->
add('parts',EntityType::class,array(
'class' => Parts::class,
'choice_label'=>"name",
'query_builder' => function(PartsRepository $partsRepository){
return $partsRepository->getAllPartsForCarsForm();
},
'multiple' => true
));
It gives me this error
Could not determine access type for property "parts" in class
"AppBundle\Entity\Cars".
Here is my entity Cars
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Cars
*
* #ORM\Table(name="cars")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CarsRepository")
*/
class Cars
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="Make", type="string", length=255)
*/
private $make;
/**
* #var string
*
* #ORM\Column(name="Model", type="string", length=255)
*/
private $model;
/**
* #var int
*
* #ORM\Column(name="TravelledDistance", type="bigint")
*/
private $travelledDistance;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
* #ORM\JoinTable(
* name="Parts_Cars",
* joinColumns={
* #ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
* })
*/
private $parts;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set make
*
* #param string $make
*
* #return Cars
*/
public function setMake($make)
{
$this->make = $make;
return $this;
}
/**
* Get make
*
* #return string
*/
public function getMake()
{
return $this->make;
}
/**
* Set model
*
* #param string $model
*
* #return Cars
*/
public function setModel($model)
{
$this->model = $model;
return $this;
}
/**
* Get model
*
* #return string
*/
public function getModel()
{
return $this->model;
}
/**
* Set travelledDistance
*
* #param integer $travelledDistance
*
* #return Cars
*/
public function setTravelledDistance($travelledDistance)
{
$this->travelledDistance = $travelledDistance;
return $this;
}
/**
* Get travelledDistance
*
* #return int
*/
public function getTravelledDistance()
{
return $this->travelledDistance;
}
/**
* #return mixed
*/
public function getParts()
{
return $this->parts;
}
}
And in case it matters here is my Parts entity
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Parts
*
* #ORM\Table(name="parts")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PartsRepository")
*/
class Parts
{
/**
* #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="Price", type="decimal", precision=10, scale=2)
*/
private $price;
/**
* #var int
*
* #ORM\Column(name="Quantity", type="integer")
*/
private $quantity;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Suppliers", inversedBy="parts")
* #ORM\JoinColumn(name="Supplier_Id", referencedColumnName="id")
*/
private $supplier;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Cars", mappedBy="parts")
*/
private $cars;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Parts
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set price
*
* #param string $price
*
* #return Parts
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set quantity
*
* #param integer $quantity
*
* #return Parts
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* #return int
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* #return mixed
*/
public function getSupplier()
{
return $this->supplier;
}
/**
* #return mixed
*/
public function getCars()
{
return $this->cars;
}
public function __toString()
{
return $this->getName();
}
}
To save time here is the mapping between the 2 entities as well as the property parts in Cars
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
* #ORM\JoinTable(
* name="Parts_Cars",
* joinColumns={
* #ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
* })
*/
private $parts;
and In Parts
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Cars", mappedBy="parts")
*/
private $cars;
Here is the newAction in CarsController
/**
* Creates a new car entity.
*
* #Route("/new", name="cars_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$carsRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Cars');
$car = new Cars();
$form = $this->createForm('AppBundle\Form\CarsType', $car);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($car);
$em->flush();
return $this->redirectToRoute('cars_show', array('id' => $car->getId()));
}
return $this->render('cars/new.html.twig', array(
'car' => $car,
'form' => $form->createView(),
));
}
My question is - How can I make it so that I can create new Car with several Parts and to save the relationship in the database so that when I retrieve the Car I can get the parts as well?
Basically how to make it so when I create a new car the relationship is saved in the parts_cars table which holds the id's?
Let Doctrine do the JOIN work
Since you're doing a ManyToMany (EntityToEntity), the #JoinColumn directives are not needed.
Try removing it from the Cars entity.
Cars
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
*/
$parts
The only cases in which you need to specify the JoinColumns are:
Joining against self
Joining where the primary key is not the Entity ID.
Need to define fields in the join_table
Would be MUCH easier in this case to do A OneToMany J ManyToOne B
Since you're doing none of the above, Doctrine is having trouble accessing the Entities' IDENTITY fields for the join.
I've been running into a problem when I'm trying to create a list of Movies with specific variable Genre. For example, all Movies with Genre "romance" and so on.
The error is:
ContextErrorException: Notice: Undefined index: genre in /(...)/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php
Entity Genre looks like this:
/**
* Genre entity.
*
*/
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Genre.
*
* #package Model
* #ORM\Table(name="genre")
* #ORM\Entity(repositoryClass="AppBundle\Repository\Genre")
*/
class Genre
{
/**
* Id.
*
* #ORM\Id
* #ORM\Column(
* type="integer",
* nullable=false,
* options={
* "unsigned" = true
* }
* )
* #ORM\GeneratedValue(strategy="IDENTITY")
*
* #var integer $id
*/
private $id;
/**
* Name.
*
* #ORM\Column(
* name="name",
* type="string",
* length=128,
* nullable=false
* )
*
* #var string $name
*/
private $name;
/**
* Movies array
*
* #ORM\OneToMany(
* targetEntity="AppBundle\Entity\Movie",
* mappedBy="genre"
* )
*/
protected $movies;
/**
* Add movies.
*
* #param \AppBundle\Entity\Movie $movies Movies
*
* #return mixed
*/
public function addMovie(\AppBundle\Entity\Movie $movies)
{
$this->movies[] = $movies;
}
/**
* Remove movies
*
* #param \AppBundle\Entity\Movie $movies Movies
*
* #return mixed
*/
public function removeAnswer(\AppBundle\Entity\Movie $movies)
{
$this->movies->removeElement($movies);
}
/**
* Get movies.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMovies()
{
return $this->movies;
}
/**
* Constructor
*/
public function __construct()
{
$this->movies = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Remove movies
*
* #param \AppBundle\Entity\Movie $movies Movies
*
* #return mixed
*/
public function removeMovie(\AppBundle\Entity\Movie $movies)
{
$this->movies->removeElement($movies);
}
/**
* Get Id.
*
* #return integer Result
*/
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
/**
* Set name.
*
* #param string $name Name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name.
*
* #return string Name
*/
public function getName()
{
return $this->name;
}
}
While movie looks like this:
/**
* Movie entity.
*/
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Movie.
*
* #package Model
* #ORM\Table(name="movies")
* #ORM\Entity(repositoryClass="AppBundle\Repository\Movie")
*/
class Movie
{
/**
* Id.
*
* #ORM\Id
* #ORM\Column(
* type="integer",
* nullable=false,
* options={
* "unsigned" = true
* }
* )
* #ORM\GeneratedValue(strategy="IDENTITY")
*
* #var integer $id
*/
private $id;
/**
* Title.
*
* #ORM\Column(
* name="title",
* type="string",
* length=255,
* nullable=false
* )
*
* #var string $title
*/
private $title;
/**
* Notes.
*
* #ORM\Column(
* name="notes",
* type="text",
* nullable=true
* )
*
* #var string $notes
*/
private $notes;
/**
* Genre array
*
* #ORM\ManyToOne(targetEntity="Genre")
* #ORM\JoinColumn(name="genre_id", referencedColumnName="id")
* )
*
* #var \Doctrine\Common\Collections\ArrayCollection $genres
*/
protected $genres;
/**
* Constructor.
*/
public function __construct()
{
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id.
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param integer $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Set title.
*
* #param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Get title.
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set notes.
*
* #param string $notes
*/
public function setNotes($notes)
{
$this->notes = $notes;
}
/**
* Get notes.
*
* #return string
*/
public function getNotes()
{
return $this->notes;
}
/**
* Add genre
*
* #param \AppBundle\Entity\Genre $genres
* #return Movie
*/
public function addGenre(\AppBundle\Entity\Genre $genres)
{
$this->genres[] = $genres;
return $this;
}
/**
* Remove genre
*
* #param \AppBundle\Entity\Genre $genres
*/
public function removeGenre(\AppBundle\Entity\Genre $genres)
{
$this->generes->removeElement($generes);
}
/**
* Get genre
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getGenre()
{
return $this->genres;
}
/**
* Set genre
*
* #param \AppBundle\Entity\Genre $genres
* #return Movie
*/
public function setGenre(\AppBundle\Entity\Genre $genres = null)
{
$this->genres = $genres;
return $this;
}
And while trying to do this, I use this in GenreController:
public function viewAction(Genre $genre)
{
if (!$genre) {
throw new NotFoundHttpException('Genre not found!');
}
$movies= $genre->getMovies();
return $this->templating->renderResponse(
'AppBundle:Genre:view.html.twig',
array('genre' => $genre)
);
}
Now every time I try to generate the page, I get a error message:
ContextErrorException: Notice: Undefined index: genre in /home/(...)/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1758
It's a first time I'm doing something like this, so I'm fully aware it's probably full of errors, but I have no idea where this one is coming from, so it's really hard for me to do anything about it. I would appreciate, if someone would show me my mistakes.
The entity name is Genre, but you reference it as Genere in some parts of the code
I am new to Symfony. I am currently using symfony2.4 .
where I stuck -
I have one scenario. In which I have to show simple listing in twing file. The data comes from database. This data comes from the two joined tables.
First table is Teams
id
name
nickname
country_id
Second table is Country
id
name
I want to print data like this
Name | Nickname | Country(name)
Mumbai Indians| MI | India
New Royals | NR | India
So What I do in my twing file :
<table border=1>
<tr>
<th>Name</th>
<th>Nickname</th>
<th>Country</th>
</tr>
{% for team in teams %}
<tr>
<td>{{ team.name }}</td>
<td>{{ team.nickname }}</td>
<td>{{ team.country }}</td> <<<<<<<<<<<
</tr>
{% endfor %}
So Here country is not working
This is my controller code
$teams = $this->getDoctrine()
->getRepository('AdminSporteventsBundle:Teams')
->findAll();
if (!$teams) {
throw $this->createNotFoundException('No news found');
}
$build['teams'] = $teams;
return $this->render('AdminSporteventsBundle:Teams:teams_list.html.twig', $build);
EDIT
As requested Teams.php (Entity)
namespace Admin\SporteventsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Teams
*
* #ORM\Table(name="teams", uniqueConstraints={#ORM\UniqueConstraint(name="uq_teams_name_sport_id", columns={"sport_id", "name"})}, indexes={#ORM\Index(name="idx_teams_by_sport_id", columns={"sport_id"}), #ORM\Index(name="idx_teams_by_sport_id_country_id", columns={"sport_id", "country_id"}), #ORM\Index(name="idx_teams_not_deleted", columns={"deleted"}), #ORM\Index(name="IDX_96C22258F92F3E70", columns={"country_id"}), #ORM\Index(name="IDX_96C222581177C375", columns={"information_page_id"}), #ORM\Index(name="IDX_96C222586D947EBB", columns={"logo_image_id"})})
* #ORM\Entity
*/
class Teams
{
/**
* #var integer
*
* #ORM\Column(name="team_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="teams_team_id_seq", allocationSize=1, initialValue=1)
*/
private $teamId;
/**
* #var string
*
* #ORM\Column(name="name", type="string", nullable=false)
*/
private $name;
/**
* #var boolean
*
* #ORM\Column(name="deleted", type="boolean", nullable=false)
*/
private $deleted;
/**
* #var integer
*
* #ORM\Column(name="editable_pages_page_id", type="integer", nullable=true)
*/
private $editablePagesPageId;
/**
* #var string
*
* #ORM\Column(name="nickname", type="string", nullable=true)
*/
private $nickname;
/**
* #var \Admin\SporteventsBundle\Entity\Countries
*
* #ORM\ManyToOne(targetEntity="Admin\SporteventsBundle\Entity\Countries")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="country_id", referencedColumnName="country_id")
* })
*/
private $country;
/**
* #var \Admin\SporteventsBundle\Entity\InformationPages
*
* #ORM\ManyToOne(targetEntity="Admin\SporteventsBundle\Entity\InformationPages")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="information_page_id", referencedColumnName="information_page_id")
* })
*/
private $informationPage;
/**
* #var \Admin\SporteventsBundle\Entity\Images
*
* #ORM\ManyToOne(targetEntity="Admin\SporteventsBundle\Entity\Images")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="logo_image_id", referencedColumnName="image_id")
* })
*/
private $logoImage;
/**
* #var \Admin\SporteventsBundle\Entity\Sports
*
* #ORM\ManyToOne(targetEntity="Admin\SporteventsBundle\Entity\Sports")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="sport_id", referencedColumnName="sport_id")
* })
*/
private $sport;
/**
* Get teamId
*
* #return integer
*/
public function getTeamId()
{
return $this->teamId;
}
/**
* Set name
*
* #param string $name
* #return Teams
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return Teams
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Set editablePagesPageId
*
* #param integer $editablePagesPageId
* #return Teams
*/
public function setEditablePagesPageId($editablePagesPageId)
{
$this->editablePagesPageId = $editablePagesPageId;
return $this;
}
/**
* Get editablePagesPageId
*
* #return integer
*/
public function getEditablePagesPageId()
{
return $this->editablePagesPageId;
}
/**
* Set nickname
*
* #param string $nickname
* #return Teams
*/
public function setNickname($nickname)
{
$this->nickname = $nickname;
return $this;
}
/**
* Get nickname
*
* #return string
*/
public function getNickname()
{
return $this->nickname;
}
/**
* Set country
*
* #param \Admin\SporteventsBundle\Entity\Countries $country
* #return Teams
*/
public function setCountry(\Admin\SporteventsBundle\Entity\Countries $country = null)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* #return \Admin\SporteventsBundle\Entity\Countries
*/
public function getCountry()
{
return $this->country;
}
/**
* Set informationPage
*
* #param \Admin\SporteventsBundle\Entity\InformationPages $informationPage
* #return Teams
*/
public function setInformationPage(\Admin\SporteventsBundle\Entity\InformationPages $informationPage = null)
{
$this->informationPage = $informationPage;
return $this;
}
/**
* Get informationPage
*
* #return \Admin\SporteventsBundle\Entity\InformationPages
*/
public function getInformationPage()
{
return $this->informationPage;
}
/**
* Set logoImage
*
* #param \Admin\SporteventsBundle\Entity\Images $logoImage
* #return Teams
*/
public function setLogoImage(\Admin\SporteventsBundle\Entity\Images $logoImage = null)
{
$this->logoImage = $logoImage;
return $this;
}
/**
* Get logoImage
*
* #return \Admin\SporteventsBundle\Entity\Images
*/
public function getLogoImage()
{
return $this->logoImage;
}
/**
* Set sport
*
* #param \Admin\SporteventsBundle\Entity\Sports $sport
* #return Teams
*/
public function setSport(\Admin\SporteventsBundle\Entity\Sports $sport = null)
{
$this->sport = $sport;
return $this;
}
/**
* Get sport
*
* #return \Admin\SporteventsBundle\Entity\Sports
*/
public function getSport()
{
return $this->sport;
}
public function __toString()
{
return $this->name;
}
}
EDIT Countries.php (Entity)
namespace Admin\SporteventsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Countries
*
* #ORM\Table(name="countries", uniqueConstraints={#ORM\UniqueConstraint(name="uq_countries_name", columns={"name"})})
* #ORM\Entity
/
class Countries
{
/*
* #var integer
*
* #ORM\Column(name="country_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="countries_country_id_seq", allocationSize=1, initialValue=1)
*/
private $countryId;
/**
* #var string
*
* #ORM\Column(name="name", type="string", nullable=false)
*/
private $name;
/**
* Get countryId
*
* #return integer
*/
public function getCountryId()
{
return $this->countryId;
}
/**
* Set name
*
* #param string $name
* #return Countries
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
public function __toString()
{
return $this->name;
}
}
You need to do {{ team.country.name }} assuming you have set your relationships up properly.
Updated to reflect entity code.
This part:
/**
* #var \Admin\SporteventsBundle\Entity\Countries
*
* #ORM\ManyToOne(targetEntity="Admin\SporteventsBundle\Entity\Countries")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="country_id", referencedColumnName="country_id")
* })
*/
private $country;
need to be changed to:
/**
* #var \Admin\SporteventsBundle\Entity\Countries
*
* #ORM\ManyToOne(targetEntity="Admin\SporteventsBundle\Entity\Countries")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="country_id", referencedColumnName="id")
* })
*/
private $country;
as referencedColumnName should be id, not country_id
By doing as above, you will create the relationship properly then in your twig file, you can use:
{{ team.country.name }}
Hope this help :)
Yo have mistake in the teams entity at join column annotation. Referencedcolumn generally is id(what's your country primary key). Then try to access country like this
You need to do {{ team.country.name }} in twig assuming you have set your relationships up proper
In the Teams Entity , at the $country field, try using the following to set the relationship:
/**
* #var \Admin\SporteventsBundle\Entity\Countries
*
* #ORM\ManyToOne(targetEntity="Admin\SporteventsBundle\Entity\Countries")
* #ORM\JoinColumn(name="country_id", referencedColumnName="country_id")
*/
private $country;
and then you can access the name of your country by typing the following in twig:
{{ team.country.name }}
maybe it's an array , and you must scan it?
{% for country in team.country %}
{{ country.name }}
{% endfor %}
I have a database with a table users with fields: user_id, username, password, ... . I also have a table players with player_name, player_position, ... AND a FK user_id.
Image relationship:
I genered the entities from the database but now I would like to get the player from user like this $user->getPlayer(). And doctrine didn't generate player in Users entity, only user in Players Entity.
This is what I have now:
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Players")
* #JoinColumn(name="user_id", referencedColumnName="userId")
*/
private $player;
/**
* Get player
*
* #return \VolleyScout\VolleyScoutBundle\Entity\Players
*/
public function getPlayer() {
return $this->player;
}
/**
* Set player
*
* #param \VolleyScout\VolleyScoutBundle\Entity\Players $player
* #return Users
*/
public function setPlayer(\VolleyScout\VolleyScoutBundle\Entity\Players $player = null){
$this->player = $player;
return $this;
}
But when I try $user->getPlayer() I always get null. (And the user_id is in players table)
UPDATE:
My Players Entity:
<?php
namespace VolleyScout\VolleyScoutBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Players
*
* #ORM\Table(name="players", indexes={#ORM\Index(name="fk_players_users1_idx", columns={"user_id"}), #ORM\Index(name="fk_players_teams1_idx", columns={"team_id"}), #ORM\Index(name="fk_players_myteam1_idx", columns={"myteam_id"})})
* #ORM\Entity
*/
class Players
{
/**
* #var string
*
* #ORM\Column(name="player_name", type="string", length=255, nullable=false)
*/
private $playerName;
/**
* #var string
*
* #ORM\Column(name="player_licensenumber", type="string", length=45, nullable=false)
*/
private $playerLicensenumber;
/**
* #var string
*
* #ORM\Column(name="player_position", type="string", nullable=false)
*/
private $playerPosition;
/**
* #var integer
*
* #ORM\Column(name="player_birthyear", type="integer", nullable=true)
*/
private $playerBirthyear;
/**
* #var integer
*
* #ORM\Column(name="player_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $playerId;
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Myteam
*
* #ORM\ManyToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Myteam")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="myteam_id", referencedColumnName="myteam_id")
* })
*/
private $myteam;
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Teams
*
* #ORM\ManyToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Teams")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="team_id", referencedColumnName="team_id")
* })
*/
private $team;
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Users
*
* #ORM\ManyToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
private $user;
/**
* Set playerName
*
* #param string $playerName
* #return Players
*/
public function setPlayerName($playerName)
{
$this->playerName = $playerName;
return $this;
}
/**
* Get playerName
*
* #return string
*/
public function getPlayerName()
{
return $this->playerName;
}
/**
* Set playerLicensenumber
*
* #param string $playerLicensenumber
* #return Players
*/
public function setPlayerLicensenumber($playerLicensenumber)
{
$this->playerLicensenumber = $playerLicensenumber;
return $this;
}
/**
* Get playerLicensenumber
*
* #return string
*/
public function getPlayerLicensenumber()
{
return $this->playerLicensenumber;
}
/**
* Set playerPosition
*
* #param string $playerPosition
* #return Players
*/
public function setPlayerPosition($playerPosition)
{
$this->playerPosition = $playerPosition;
return $this;
}
/**
* Get playerPosition
*
* #return string
*/
public function getPlayerPosition()
{
return $this->playerPosition;
}
/**
* Set playerBirthyear
*
* #param integer $playerBirthyear
* #return Players
*/
public function setPlayerBirthyear($playerBirthyear)
{
$this->playerBirthyear = $playerBirthyear;
return $this;
}
/**
* Get playerBirthyear
*
* #return integer
*/
public function getPlayerBirthyear()
{
return $this->playerBirthyear;
}
/**
* Get playerId
*
* #return integer
*/
public function getPlayerId()
{
return $this->playerId;
}
/**
* Set myteam
*
* #param \VolleyScout\VolleyScoutBundle\Entity\Myteam $myteam
* #return Players
*/
public function setMyteam(\VolleyScout\VolleyScoutBundle\Entity\Myteam $myteam = null)
{
$this->myteam = $myteam;
return $this;
}
/**
* Get myteam
*
* #return \VolleyScout\VolleyScoutBundle\Entity\Myteam
*/
public function getMyteam()
{
return $this->myteam;
}
/**
* Set team
*
* #param \VolleyScout\VolleyScoutBundle\Entity\Teams $team
* #return Players
*/
public function setTeam(\VolleyScout\VolleyScoutBundle\Entity\Teams $team = null)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* #return \VolleyScout\VolleyScoutBundle\Entity\Teams
*/
public function getTeam()
{
return $this->team;
}
/**
* Set user
*
* #param \VolleyScout\VolleyScoutBundle\Entity\Users $user
* #return Players
*/
public function setUser(\VolleyScout\VolleyScoutBundle\Entity\Users $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \VolleyScout\VolleyScoutBundle\Entity\Users
*/
public function getUser()
{
return $this->user;
}
}
UPDATE 2: In my Users Entity Class I have now:
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToMany(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Players")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
private $player;
But it still doesn't work ..
Your annotations are not set correctly (specifically, the JoinColumn). It is interesting that you aren't getting an error, but anyways... replace this:
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Players")
* #JoinColumn(name="user_id", referencedColumnName="userId")
*/
private $player;
with this:
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Players")
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
*/
private $player;
notice that your referencedColumnName should be the name as it is shown in the database, not the Doxtrine entity. Start by fixing those errors, and it should solve the problem.
UPDATE
This is a very different setup it you want a manyToOne relationship.
/**
* #var \VolleyScout\VolleyScoutBundle\Entity\Players
*
* #ORM\OneToMany(targetEntity="Players", mappedBy="user_id")
*/
private $players;
public function __construct()
{
$this->players = new ArrayCollection();
}
Because $players can now have many values, it should be set as an ArrayCollection. I also made the variable $players instead of $player, for ease of readability.
You should really familiarize yourself with the Symfony Docs, this is a very simple problem that is described very clear in the Symfony docs
I have the problem when I want to select for example all the categories in my table that Doctrine only selects the first row data.
For example:
I have 3 categories (id: 1, 2 & 3). I want to select all the
categories by doing this: $categories =
$entityManager->getRepository('ReuzzeReuzzeBundle:Categories')
->findAll();
What I get now is: 3 times the first entity!
I have 3 categories (id: 1, 2 & 3). I want to select the category
with id = 2 by doing this: $category =
$entityManager->getRepository('ReuzzeReuzzeBundle:Categories')->findOneByCategoryId(2);
then I get again the first category with id = 1 ...
Is this is a settings problem or other ... ? Can somebody help me with this? It's very annoying when you can't select all the data :/
UPDATE:
My Entity Categories Class:
<?php
namespace Reuzze\ReuzzeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Categories
*
* #ORM\Table(name="categories", indexes={#ORM\Index(name="fk_categories_categories1_idx", columns={"category_parentid"})})
* #ORM\Entity
*/
class Categories
{
/**
* #var boolean
*
* #ORM\Column(name="category_id", type="boolean")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $categoryId;
/**
* #var string
*
* #ORM\Column(name="category_name", type="string", length=45, nullable=false)
*/
private $categoryName;
/**
* #var string
*
* #ORM\Column(name="category_description", type="string", length=255, nullable=false)
*/
private $categoryDescription;
/**
* #var \DateTime
*
* #ORM\Column(name="category_created", type="datetime", nullable=false)
*/
private $categoryCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="category_modified", type="datetime", nullable=true)
*/
private $categoryModified;
/**
* #var \DateTime
*
* #ORM\Column(name="category_deleted", type="datetime", nullable=true)
*/
private $categoryDeleted;
/**
* #var \Reuzze\ReuzzeBundle\Entity\Categories
*
* #ORM\ManyToOne(targetEntity="Reuzze\ReuzzeBundle\Entity\Categories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_parentid", referencedColumnName="category_id")
* })
*/
private $categoryParentid;
/**
* Get categoryId
*
* #return boolean
*/
public function getCategoryId()
{
return $this->categoryId;
}
/**
* Set categoryName
*
* #param string $categoryName
* #return Categories
*/
public function setCategoryName($categoryName)
{
$this->categoryName = $categoryName;
return $this;
}
/**
* Get categoryName
*
* #return string
*/
public function getCategoryName()
{
return $this->categoryName;
}
/**
* Set categoryDescription
*
* #param string $categoryDescription
* #return Categories
*/
public function setCategoryDescription($categoryDescription)
{
$this->categoryDescription = $categoryDescription;
return $this;
}
/**
* Get categoryDescription
*
* #return string
*/
public function getCategoryDescription()
{
return $this->categoryDescription;
}
/**
* Set categoryCreated
*
* #param \DateTime $categoryCreated
* #return Categories
*/
public function setCategoryCreated($categoryCreated)
{
$this->categoryCreated = $categoryCreated;
return $this;
}
/**
* Get categoryCreated
*
* #return \DateTime
*/
public function getCategoryCreated()
{
return $this->categoryCreated;
}
/**
* Set categoryModified
*
* #param \DateTime $categoryModified
* #return Categories
*/
public function setCategoryModified($categoryModified)
{
$this->categoryModified = $categoryModified;
return $this;
}
/**
* Get categoryModified
*
* #return \DateTime
*/
public function getCategoryModified()
{
return $this->categoryModified;
}
/**
* Set categoryDeleted
*
* #param \DateTime $categoryDeleted
* #return Categories
*/
public function setCategoryDeleted($categoryDeleted)
{
$this->categoryDeleted = $categoryDeleted;
return $this;
}
/**
* Get categoryDeleted
*
* #return \DateTime
*/
public function getCategoryDeleted()
{
return $this->categoryDeleted;
}
/**
* Set categoryParentid
*
* #param \Reuzze\ReuzzeBundle\Entity\Categories $categoryParentid
* #return Categories
*/
public function setCategoryParentid(\Reuzze\ReuzzeBundle\Entity\Categories $categoryParentid = null)
{
$this->categoryParentid = $categoryParentid;
return $this;
}
/**
* Get categoryParentid
*
* #return \Reuzze\ReuzzeBundle\Entity\Categories
*/
public function getCategoryParentid()
{
return $this->categoryParentid;
}
}
It looks like your problem is with you annotations definition of your categoryId. You have defined it as a boolean. This should be an integer. That would probably be why you are only getting the category with id 1.