I'm trying to learn Doctrine.
I'm trying to update my database with the last generated entity.
I generated the entity with doctrine:generate:entity
here it is:
<?php
namespace NRtworks\ChartOfAccountsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Lasttest
*
* #ORM\Table()
* #ORM\Entity
*/
class Lasttest
{
/**
* #var integer
*
* #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;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Lasttest
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
?>
So basic stuff, I did not change anything.
Then I'd like doctrine to generate the table in my sql database but here is the answer to:
doctrine:mapping:info -> you do not have any mapped entity
doctrine:schema:update -> you do not have metadata class to process
doctrine:generate:entities RandomnameBundle -> does not contain any mapped entities
Any hint ?
Try changing doctrine orm mapping from auto_mapping to manual.
Example shown below:
doctrine:
...
orm:
...
auto_mapping: true
TO
orm:
entity_managers:
default:
mappings:
NRtworks\ChartOfAccountsBundle: ~
http://docs.doctrine-project.org/en/2.0.x/reference/annotations-reference.html#annref-table
#ORM\Table requires table name.
Required attributes:
name: Name of the table
I did not exactly found the problem but it's solved
-> I have updated Symfony to its last version
Related
I am using Knp/DoctrineBehaviors to translate my database content.
I followed the manual and created 2 entities, 1 for non-translatable content and the other for translatable fields.
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;
/**
* Class Test
* #package App\Entity
* #ORM\Entity()
*/
class Test implements TranslatableInterface
{
use TranslatableTrait;
/**
* #var integer
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id()
*/
private $id;
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
}
and the Translation entity:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;
/**
* Class TestTranslation
* #package App\Entity
* #ORM\Entity()
*/
class TestTranslation implements TranslationInterface
{
use TranslationTrait;
/**
* #var
* #ORM\Column(type="string")
*/
private $name;
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #param mixed $name
*/
public function setName($name): void
{
$this->name = $name;
}
}
I also added the Bundle in my bundles.php file.
But when I run the command php bin/console doctrine:schema:update --force to create the table in give the error: No identifier/primary key specified for Entity "App\Entity\TestTranslation". Every Entity must have an identifier/p rimary key.
A primary key is missing in your entity "TestTranslation".
In doctrine every entity class must have an identifier/primary key. You can select the field that serves as the identifier with the #Id() annotation or in your case : #ORM\Id().
For example, add this to your entity :
/**
* #var integer
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id()
*/
private $id;
And then, you can play the command: php bin/console d:s:u --force
In my case, Symfony 3.4, I forgot to register the bundle and set the config.yml as:
knp_doctrine_behaviors:
translatable: true
I use FOSRestBundle with JMSSerializerBundle in my web service.
Here is a function in my action controller that returns a list of roles. I don't know how to return a "parent_id" field in this list.
<?php
use FOS\RestBundle\Controller\FOSRestController;
class RoleController extends FOSRestController
{
...
/**
* List all roles.
*
* #Annotations\View()
*
* #return array
*/
public function getRolesAction()
{
$roles = $this->repository->findRoles();
$view = $this->view($roles, 200);
return $this->handleView($view);
}
...
}
Here is my role entity. It has properties: id, name and parent. Parent is a role.
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\RoleRepository")
*/
class Role
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Role")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
// + getters and setters
...
}
Here is my serializer config file:
AppBundle\Entity\Role:
exclusion_policy: ALL
properties:
id:
expose: true
type: integer
xml_attribute: true
name:
expose: true
type: string
Now getRolesAction in action controller will output JSON with id and name properties. How to add parent_id property to the serializer output?
You could use something like:
/**
* #Serializer\VirtualProperty
* #Serializer\Type("integer")
* #Serializer\SerializedName("parent_id")
*
* #return integer
*/
public function getParentId()
{
return $this->parent->getId();
}
I can't tell you how to transfer the annotation in your config (probably YAML) format, but you'll be able to do that.
IMPORTANT
This only works for serialization - so don't expect this attribute to be deserialized later!!
Alternative:
If you only want to achieve the result you were asking for you could add this to your attribute:
/**
* #Accessor(getter="getParentId",setter="setParent") */
* #Serializer\Type("integer")
* #Serializer\SerializedName("parent_id")
*/
private $parent;
and additionally another getter:
/**
*
* #return integer
*/
public function getParentId()
{
return $this->parent->getId();
}
With the accessor you tell JMS from which getter to get the result to serialize while still being able to use the setter for deserialization.
i working with Symfony2 and Doctrine ORM using MySql.
When i try uo use:
php app/console doctrine:migration:diff
i have this error:
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'blog.post' already exists.
My code in Post.php (i use annotation) is:
namespace Blog\ModelBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Post
*
* #ORM\Table()
* #ORM\Entity
*/
class Post extends Timestampable
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=150)
* #Assert\NotBlank
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="body", type="text")
* #Assert\NotBlank
*/
private $body;
/**
* #var Author
* #ORM\ManyToOne (targetEntity="Author", inversedBy="posts")
* #ORM\JoinColumn (name="author_id", referencedColumnName="id", nullable=false)
* #Assert\NotBlank
*/
private $author;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set body
*
* #param string $body
* #return Post
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Get body
*
* #return string
*/
public function getBody()
{
return $this->body;
}
/**
* Set author
*
* #param \Blog\ModelBundle\Entity\Author $author
* #return Post
*/
public function setAuthor(Author $author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return \Blog\ModelBundle\Entity\Author
*/
public function getAuthor()
{
return $this->author;
}
}
I try to define * #ORM\Table(name="Post").
Can you help me with this type of error.
Sorry for my bad english.
Your mapping looks incorrect. The ManyToOne declaration does not need an inversedBy attribute if you're not using a join table. You also do not need to specify the #var since it already knows it's using the entity. Try this:
/**
* #ORM\ManyToOne(targetEntity="Author")
* #ORM\JoinColumn(name="author_id", referencedColumnName="id")
**/
private $author;
One other thing to do is to check that you're not trying to declare the same entity in another bundle, this will also cause the "table already exists" error.
Also, to avoid using full path entity references in the getter and setter, just include the entity in the use statemnets at the top of the class, then you only need write the entity name:
/**
* set Author
*
* #param Author $author
*
* #return Post
/**
I'm using the excellent doctrine extension uploadable. I can upload one file per entity just fine, but how can I upload two different files on the same entity?
* #Gedmo\Uploadable(path="uploads/articles", appendNumber=true, filenameGenerator="SHA1")
class Article
{
* #ORM\Column(name="photo", type="string", length=255)
* #Gedmo\UploadableFilePath
private $photo
* #ORM\Column(name="pdf", type="string", length=255)
* #Gedmo\UploadableFilePath
private $pdf
On my controller I have:
$uploadableManager->markEntityToUpload($article, $article->getPhoto());
$uploadableManager->markEntityToUpload($article, $article->getPdf());
Only the last file is uploaded and saved to the database. How can I do this?
You probably confused something.
You have Article entity with two fields: photo and pdf, but there is no $materia entity. You probably should change $materia to $article. But this won't work because #Uploadable cannot upload multiple files for the same entity.
Hint: use VichUploaderBundle for Doctrine file uploads handling
UPD: Here is example class.
<?php
namespace Acme\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity
* #ORM\Table(name="article")
* #Vich\Uploadable
*/
class Article
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
// ..... other fields
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="article_photo", fileNameProperty="photoName")
*
* #var File
*/
private $photoFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $photoName;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="article_pdf", fileNameProperty="pdfName")
*
* #var File
*/
private $pdfFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $pdfName;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* #param \DateTime $updatedAt
* #return Article
*/
public function setUpdatedAt(\DateTime $updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $photo
*
* #return Article
*/
public function setPhotoFile(File $photo = null)
{
$this->photoFile = $photo;
if ($photo) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTime('now');
}
return $this;
}
/**
* #return File
*/
public function getPhotoFile()
{
return $this->photoFile;
}
/**
* #param string $photoName
*
* #return Article
*/
public function setPhotoName($photoName)
{
$this->photoName = $photoName;
return $this;
}
/**
* #return string
*/
public function getPhotoName()
{
return $this->photoName;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $pdf
*
* #return Article
*/
public function setPdfFile(File $pdf = null)
{
$this->pdfFile = $pdf;
if ($pdf) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTime('now');
}
return $this;
}
/**
* #return File
*/
public function getPdfFile()
{
return $this->pdfFile;
}
/**
* #param string $pdfName
*
* #return Article
*/
public function setPdfName($pdfName)
{
$this->pdfName = $pdfName;
return $this;
}
/**
* #return string
*/
public function getPdfName()
{
return $this->pdfName;
}
}
And you need to configure VichUploader this way:
# app/config/config.yml
vich_uploader:
db_driver: orm
mappings:
article_photo:
uri_prefix: /images/articles/photos
upload_destination: %kernel.root_dir%/../web/images/articles/photos
article_pdf:
uri_prefix: /images/articles/pdfs
upload_destination: %kernel.root_dir%/../web/images/articles/pdfs
Be attentive. You can get confused with configuration, mappings, methods... just read manual carefully and thoughtly. https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/usage.md
I have followed One-to-Many relation not working and created a one to many relationship
i have a users table where i have following fields
- id(primary key)
- name
- pwd
i have attachments table where user can upload more than one file i.e one user_id contains multiple files
- id
- user_id(foreignkey)
- path
my user entity contains the following code
namespace Repair\StoreBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* users
* #ORM\Entity(repositoryClass="Repair\StoreBundle\Entity\usersRepository")
*/
class users
{
/**
* #var integer
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
--some code --
/**
* #ORM\OneToMany(targetEntity="attachments", mappedBy="user_id")
*/
private $attachments;
public function __construct()
{
$this->attachments= new ArrayCollection();
}
/**
* Add attachments
*
* #param \Repair\StoreBundle\Entity\attachments $attachments
* #return users
*/
public function addAttachment(\Repair\StoreBundle\Entity\attachments $attachments)
{
$this->attachments[] = $attachments;
return $this;
}
/**
* Remove attachments
*
* #param \Repair\StoreBundle\Entity\attachments $attachments
*/
public function removeAttachment(\Repair\StoreBundle\Entity\attachments $attachments)
{
$this->attachments->removeElement($attachments);
}
/**
* Get attachments
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAttachments()
{
return $this->attachments;
}
this is my attachments entity
namespace Repair\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* attachments
*/
class attachments
{
-- some code for id--
private $id;
/**
* #var integer
* #ORM\Column(name="user_id", type="integer", nullable=false)
* #ORM\ManyToOne(targetEntity="users", inversedBy="users")
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
*/
protected $userId;
public function getId()
{
return $this->id;
}
/**
* Set userId
* #param integer $userId
* #return attachments
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return integer
*/
public function getuserId()
{
return $this->userId;
}
--Some code for paths --
}
It is not displaying any errors
but how to know whether the foriegn key is set or not i went to phpmyadmin and checked the indexes it only shows the primary keys.please say whether i did correct or not and how to check whether foreign key is set or not
problem is in your annotations. In your attachment entity you should have annotation like this.
* #ORM\ManyToOne(targetEntity="users", inversedBy="annotations")
you don't have to have join column annotation. But if you want to have it there, it should look like this.
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
Also it shouldn't be called user_id but user, because doctrine takes it as whole entity.