I'm trying to relate an entity in one bundle with another in another bundle to make the second one independent from the first one, and be able to reuse it.
I'm following this documentation and this StackOverflows answer.
In the reusable bundle I have a Folder, File a that belongs to the folder and and interface like this:
namespace Acme\FolderBundle\Entity;
/**
* #ORM\Entity
*/
class Folder implements FolderInterface
{
// Has many files
}
namespace Acme\FolderBundle\Entity;
interface FolderInterface
{
// no methods here
}
namespace Acme\FolderBundle\Entity;
/**
* #ORM\Entity
*/
class File
{
// Belongs to one folder
}
And on the other bundle just one class:
namespace Acme\NewBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Acme\FolderBundle\Entity\Folder as BaseFolder;
use Acme\FolderBundle\Entity\FolderInterface;
/**
* #ORM\Entity
*/
class Folder extends BaseFolder implements FolderInterface
{
// Has many files
}
And the config.yml's ORM configuration:
orm:
auto_generate_proxy_classes: %kernel.debug%
auto_mapping: true
resolve_target_entities:
Acme\FolderBundle\Entity\FolderInterface: Acme\NewBundle\Entity\Folder
If I try to update my database schema, I get the following error:
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'foldersDatabase.folder' already exists.
To get this working, I have to explicitly change one of the Folder's Entities table:
namespace Acme\FolderBundle\Entity;
/**
* #ORM\Entity
* #ORM\Table(name="distributed_folder")
*/
class Folder implements FolderInterface
{
// Has many files
}
Then, everything works but I get stuck with a table in my database (distributed_folder) that is never used.
Thanks a lot in advance!!
EDIT:
Fixed the annotation in the FolderInterface
You can not make one entity extend another entity this way.
If you want to have an abstract class which contains the fields for two or more subclass entities, you should mark the abstract class as #ORM\MappedSuperclass , and make sure, it will not have the annotation #Entity. While on the subclasses , they each should have #Entity annotation , and #Table annotation with a unique name attribute.
Here is an example :
<?php
namespace Radsphere\MissionBundle\Model\Core\BaseAbstract;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\MappedSuperclass
*
* An abstract class implementation of mission
*/
abstract class AbstractMission implements MissionInterface, IntegratedPluginInterface
{
/**
* #ORM\Id()
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=36, unique=true)
*/
protected $guid;
/**
* #ORM\Column(type="string", length=255)
*/
protected $title;
/**
* #ORM\ManyToMany(targetEntity="MissionTask", cascade={"persist", "remove"})
* #ORM\JoinTable(name="mtm_mission_task",
* joinColumns={#ORM\JoinColumn(name="mission_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={#ORM\JoinColumn(name="task_id", referencedColumnName="id", onDelete="CASCADE")}
* )
*/
protected $tasks;
/**
* {#inheritDoc}
*/
public function addTask(MissionTaskInterface $missionTask)
{
$this->getTasks()->add($missionTask);
$missionTask->setMission($this);
}
/**
* {#inheritDoc}
*/
public function setTasks(Collection $tasks)
{
/** #var MissionTaskInterface $task */
foreach ($tasks as $task) {
$task->setMission($this);
}
$this->tasks = $tasks;
}
/**
* {#inheritDoc}
*/
public function getTasks()
{
$tasks = $this->tasks;
foreach ($tasks as $task) {
if ($task instanceof MissionTaskInterface) {
if (!$task->getIsEnabled()) {
/** #var $tasks Collection */
$tasks->removeElement($task);
}
}
}
return $tasks;
}
}
and the entity itself:
<?php
namespace Radsphere\MissionBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Radsphere\MissionBundle\Model\Core\BaseAbstract\AbstractMission;
/**
* Mission entity
*
* #ORM\Table(name="mission_bundle_mission", indexes={#ORM\Index(name="guid_idx", columns={"guid"})})
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="MissionRepository")
*/
class Mission extends AbstractMission
{
/**
* Constructor
*/
public function __construct()
{
$this->tasks = new ArrayCollection();
}
}
Related
I have a problem in a 2 level of inheritance structure with api-platfom but maybe with doctrine too
I have two question about this code :
doctrine is well generating a discr column in the MyParent class, but not in MyChild class for some reason... I don't think it is normal as how to know that an instance is MyChildChild if there is no discr column in MyChild ?
with api-platform, I have some errors as soon as I have 2 levels of inheritance. As soon as I remove one of the "extends MyChild" or "extends MyParent" api-platform behaviour is ok but loose the fields of the removed class (normal)
Is there something I'm doing wrong ? I have already use multiple level of inheritance with doctrine and I don't remember that I had this behaviour (only one discr column for 2 classes). And for api-platform, I'm just discovering so maybe I missed something
Thank you in advance
RV
Here is my code
// src/Entity/MyParent.php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\MyParentRepository;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\MyChild;
/**
* #ApiResource()
* #ORM\Entity(repositoryClass=MyParentRepository::class)
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({"child"="MyChild"})
*/
class MyParent
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $parentAttribute;
public function getId(): ?int
{
return $this->id;
}
public function getParentAttribute(): ?string
{
return $this->parentAttribute;
}
public function setParentAttribute(string $parentAttribute): self
{
$this->parentAttribute = $parentAttribute;
return $this;
}
}
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\MyChildRepository;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\MyChildChild;
use App\Entity\MyParent;
/**
* #ApiResource()
* #ORM\Entity(repositoryClass=MyChildRepository::class)
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({"childchild"="MyChildChild"})
*/
class MyChild extends MyParent
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $childAttribute;
public function getId(): ?int
{
return $this->id;
}
public function getChildAttribute(): ?string
{
return $this->childAttribute;
}
public function setChildAttribute(string $childAttribute): self
{
$this->childAttribute = $childAttribute;
return $this;
}
}
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\MyChildChildRepository;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\MyChild;
/**
* #ApiResource()
* #ORM\Entity(repositoryClass=MyChildChildRepository::class)
*/
class MyChildChild extends MyChild
{
/**
* #ORM\Column(type="string", length=255)
*/
private $MyChildChildAttribute;
public function getMyChildChildAttribute(): ?string
{
return $this->MyChildChildAttribute;
}
public function setMyChildChildAttribute(string $MyChildChildAttribute): self
{
$this->MyChildChildAttribute = $MyChildChildAttribute;
return $this;
}
}
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 have an already created symfony bundle. i wanted to add another bundle for my application separately. so now im facing a problem that how to extend an entity from old bundle to newly created one. i extended it normally but it giving errors.
i have these 2 bundles,
MyFirstBundle
MySecondBundle
MyFirstBundle entity,
namespace My\FirstBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
* #ORM\Table(name="companies")
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Company
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*
* #Groups({"list_companies", "company_details", "ad_details"})
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=50, nullable=true)'
*
* #Groups({"ad_details"})
*/
private $name;
MySecondBundle Entity,
namespace My\SecondBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use My\FirstBundle\Entity\Company as BaseCompany;
class Companies extends BaseCompany
{
public function __construct() {
parent::__construct();
}
}
im not sure that i can extend my entity like this. im getting error when creating forms with this entity
Class "MySecondBundle:companies" seems not to be a managed Doctrine entity. Did you forget to map it?
You need to add the doctrine annotations for the second entity as well.
/**
*
* #ORM\Table(name="companies")
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Companies extends BaseCompany
{
public function __construct() {
parent::__construct();
}
}
I trying to create CRUD panel from FOSUserBundle but i have some troubles. I mean that i created User entity for FOS and made crud panel for this entity. Now when i trying to add new user i have error like below
Neither the property "expiresAt" nor one of the methods "getExpiresAt()", "isExpiresAt()", "hasExpiresAt()", "_get()" or "_call()" exist and have public access in class "Bn\UserBundle\Entity\User".
It's my first project so please understand when i will ask for simple function, some suggestion ? What is wrong ?
<?php
namespace Bn\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table(name="fos_user")
* #ORM\Entity
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Get expiresAt
*
* #return \DateTime
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* Get credentials_expire_at
*
* #return \DateTime
*/
public function getCredentialsExpireAt()
{
return $this->credentialsExpireAt;
}
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
Now is working but i don't know why i must declare again function for getter.
I believe this means you need to add public accessors setExpiresAt() and getExpiresAt() to your User entity.
You need only add getExpiresAt to your User.php class. FOSUserBundle\User doesn't have getter for this field, but Sensio generator creates views for all fields.
public function getExpiresAt()
{
return $this->expiresAt;
}
I am using the FOSUserBundle.
This is the User Entity:
namespace Shop\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
protected $shop;
public function __construct()
{
$this->shop = 'shop';
parent::__construct();
}
public function getShop()
{
return $this->shop;
}
}
When I call getShop in the controller:
$user = $this->getUser()->getShop()
A result is null
Why does not __construct work in User class?
I expected to have 'shop' string as default
You can put a callback to iniatilize your User. Just two annotations #ORM\HasLifecycleCallbacks for the entity and #ORM\PostLoad for the method. For example:
namespace Shop\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
* #ORM\HasLifecycleCallbacks
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
protected $shop;
/**
* #ORM\PostLoad
*/
public function init()
{
$this->shop = 'shop';
parent::init();
}
public function getShop()
{
return $this->shop;
}
}
Basically __construct in doctrine entity is called directly in end user code. Doctrine does not use construct when fetch entities from database - please check that question for more details. You can persist this in database by adding mapping if you want.