As per title, what's the purpose of the new annotation #AssociationOverride and #AttributeOverride?
The only thing I can find on Doctrine website is:
#AssociationOverride and #AttributeOverride (useful for Trait and
MappedSuperclass)
By looking at the code in the commit, we can see that it is used to override a field mapping already defined in a mapped superclass / trait.
The tests included in the commit demonstrate this behaviour:
Mapped superclass
/**
* #MappedSuperclass
*/
class User
{
/**
* #Id
* #GeneratedValue
* #Column(type="integer", name="user_id", length=150)
*/
protected $id;
/**
* #Column(name="user_name", nullable=true, unique=false, length=250)
*/
protected $name;
/**
* #var ArrayCollection
*
* #ManyToMany(targetEntity="Group", inversedBy="users", cascade={"persist", "merge", "detach"})
* #JoinTable(name="users_groups",
* joinColumns={#JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;
/**
* #var Address
*
* #ManyToOne(targetEntity="Address", cascade={"persist", "merge"})
* #JoinColumn(name="address_id", referencedColumnName="id")
*/
protected $address;
...
}
Subclass using #AssociationOverride
/*
* #Entity
* #AssociationOverrides({
* #AssociationOverride(name="groups",
* joinTable=#JoinTable(
* name="users_admingroups",
* joinColumns=#JoinColumn(name="adminuser_id"),
* inverseJoinColumns=#JoinColumn(name="admingroup_id")
* )
* ),
* #AssociationOverride(name="address",
* joinColumns=#JoinColumn(
* name="adminaddress_id", referencedColumnName="id"
* )
* )
* })
*/
class Admin extends User
{
...
}
Subclass using #AttributeOverride
/**
* #Entity
* #AttributeOverrides({
* #AttributeOverride(name="id",
* column=#Column(
* name = "guest_id",
* type = "integer",
* length = 140
* )
* ),
* #AttributeOverride(name="name",
* column=#Column(
* name = "guest_name",
* nullable = false,
* unique = true,
* length = 240
* )
* )
* })
*/
class Guest extends User
{
...
}
Related
I cannot figure out how to reach this goal:
I want to have the object representation in a GET request with the related entity as json object too, while i want to send just the iri in a POST request of the parent object
/**
* #ORM\Entity(repositoryClass=CustomerRepository::class)
* #ApiResource
*/
class Customer
{
/**
* #var int|null
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #ApiProperty(
* identifier=false,
* description="ID univoco del cliente generato da un'operazione di POST"
* )
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="codice_cliente", type="string", length=20, unique=true)
* #ApiProperty(
* identifier=true,
* description="Codice identificativo del cliente.<br>Si tratta di un codice univoco che identifica il cliente all'interno dell'azienda di riferimento"
* )
*/
private $codiceCliente;
/**
* #var string|null
*
* #ORM\Column(name="ragione_sociale", type="string", length=50, nullable=true)
* #ApiProperty(description="Denominazione ufficiale del cliente")
*/
private $ragioneSociale;
/**
* #var string|null
*
* #ORM\Column(name="nome", type="string", length=50, nullable=true)
* #ApiProperty(description="Nome anagrafico del cliente")
*/
private $nome;
/**
* #var string|null
*
* #ORM\Column(name="cognome", type="string", length=50, nullable=true)
* #ApiProperty(description="Cognome anagrafico del cliente")
*/
private $cognome;
/**
* #var string|null
*
* #ORM\Column(name="codice_fiscale", type="string", length=16, nullable=true)
* #ApiProperty(description="Codice fiscale del cliente.<br>Può corrispondere a `partitaIva` in caso di azienda.")
*/
private $codiceFiscale;
/**
* #var string|null
*
* #ORM\Column(name="partita_iva", type="string", length=11, nullable=true)
* #ApiProperty(description="Partita Iva del cliente in caso di azienda.<br>È un valore numerico di 11 cifre.")
*/
private $partitaIva;
/**
* #var CustomerCategory
*
* #ORM\ManyToOne(targetEntity=CustomerCategory::class)
* #ORM\JoinColumn(name="categoria_id", referencedColumnName="codice", nullable=false)
*/
private $categoria;
/**
* #return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* #return string
*/
public function getCodiceCliente(): ?string
{
return $this->codiceCliente;
}
/**
* #param string $codiceCliente
*
* #return Customer
*/
public function setCodiceCliente(string $codiceCliente): Customer
{
$this->codiceCliente = $codiceCliente;
return $this;
}
/**
* #return string|null
*/
public function getRagioneSociale(): ?string
{
return $this->ragioneSociale;
}
/**
* #param string|null $ragioneSociale
*
* #return Customer
*/
public function setRagioneSociale(?string $ragioneSociale): Customer
{
$this->ragioneSociale = $ragioneSociale;
return $this;
}
/**
* #return string|null
*/
public function getNome(): ?string
{
return $this->nome;
}
/**
* #param string|null $nome
*
* #return Customer
*/
public function setNome(?string $nome): Customer
{
$this->nome = $nome;
return $this;
}
/**
* #return string|null
*/
public function getCognome(): ?string
{
return $this->cognome;
}
/**
* #param string|null $cognome
*
* #return Customer
*/
public function setCognome(?string $cognome): Customer
{
$this->cognome = $cognome;
return $this;
}
/**
* #return string|null
*/
public function getCodiceFiscale(): ?string
{
return $this->codiceFiscale;
}
/**
* #param string|null $codiceFiscale
*
* #return Customer
*/
public function setCodiceFiscale(?string $codiceFiscale): Customer
{
$this->codiceFiscale = $codiceFiscale;
return $this;
}
/**
* #return string|null
*/
public function getPartitaIva(): ?string
{
return $this->partitaIva;
}
/**
* #param string|null $partitaIva
*
* #return Customer
*/
public function setPartitaIva(?string $partitaIva): Customer
{
$this->partitaIva = $partitaIva;
return $this;
}
public function getCategoria(): ?CustomerCategory
{
return $this->categoria;
}
public function setCategoria(?CustomerCategory $categoria): self
{
$this->categoria = $categoria;
return $this;
}
}
/**
* #ORM\Entity(repositoryClass=CustomerCategoryRepository::class)
* #ApiResource()
*/
class CustomerCategory
{
/**
* #var string
*
* #ORM\Id
* #ORM\Column(type="string", length=10)
* #ApiProperty(identifier=true,
* description="Codice identificativo della categoria")
*/
private $codice;
/**
* #var string
*
* #ORM\Column(type="string", length=100, nullable=true)
* #ApiProperty(description="Descrizione del codice di identificazione")
*/
private $descrizione;
public function getCodice(): ?string
{
return $this->codice;
}
public function setCodice(string $codice): self
{
$this->codice = $codice;
return $this;
}
public function getDescrizione(): ?string
{
return $this->descrizione;
}
public function setDescrizione(?string $descrizione): self
{
$this->descrizione = $descrizione;
return $this;
}
}
So when i GET the Customer i want the $categoria property to be
{
codice: "10"
descrizione: "Test"
}
While when i POST/PUT/PATCH a Customer i want to refer to the CustomerCategory as the IRI of the ID as i don't have cascade persists in this case
{
"codiceCliente": "string",
"ragioneSociale": "string",
"nome": "string",
"cognome": "string",
"codiceFiscale": "string",
"partitaIva": "string",
"categoria": "/api/customer_categories/10"
}
I want also to have the correct representation on the OPEN API docs
You can get such results using a Serialization Group, except for the #id and #type being added to both Customer and to the $categoria property (API Platform automatically adds them).
First add the following to both your Entities:
use Symfony\Component\Serializer\Annotation\Groups;
To configure a Serialization Group only for the get operations of Customer:
/**
* #ORM\Entity(repositoryClass=CustomerRepository::class)
* #ApiResource(
* itemOperations={
* "get"={
* "normalization_context"={"groups"={"customer:get"}}
* },
* "patch",
* "put",
* "delete"
* },
* collectionOperations={
* "get"={
* "normalization_context"={"groups"={"customer:get"}}
* },
* "post"
* }
* )
*/
class Customer
//...
And then add #Groups({"customer:get"}) to the doc blocks of all props of Customer except $id, including $categoria. I only give one example here:
/**
* #var string|null
*
* #ORM\Column(name="ragione_sociale", type="string", length=50, nullable=true)
* #ApiProperty(description="Denominazione ufficiale del cliente")
* #Groups({"customer:get"})
*/
private $ragioneSociale;
Also add #Groups({"customer:get"}) to the doc blocks of $codice and $descrizione of CustomerCategory.
This should do the trick and leave the post, put and patch operations unchanged (expecting and returning just the iri of $categoria). It should automatically give a correct representation on the OPEN API docs.
Tip: The readme of branch chapter4-api of my tutorial also contains instructions for adding Serialization Groups two Entities related like yours, and the resulting code is in branch chapter5-api.
darkaonline/l5-swagger: 8.0.2
PHP Version: 7.3.13
zircote/swagger-php: 3.1.0
OS: Windows
I created a Contract ref object.
Now in my ContractController I want to list an array of contracts.
How can I do it?
I got this error Couldn't find constant array when trying to add type=array in OA\Items
/**
* #OA\Info(title="Contract API", version="1")
*/
class ContractController extends Controller
{
/**
* #OA\Post(
* path="/api/v1/contract/list",
* tags={"contact"},
* summary="List Contract",
* operationId="list",
* #OA\Parameter(
* name="keyword",
* in="path",
* description="keyword to search contracts",
* required=false,
* #OA\Schema(
* type="string"
* )
* ),
* #OA\Parameter(
* name="lang_code",
* in="path",
* description="lang_code define language client used",
* required=false,
* #OA\Schema(
* type="string",
* )
* ),
* #OA\Response(
* response=200,
* description="successful",
* #OA\JsonContent(
* #OA\Items(
* type=array, #This is where I got the error
* ref="#/components/schemas/Contract"
* )
* )
* ),
* #OA\Response(
* response=400,
* description="Wrong"
* )
* )
*/
public function list(Request $request)
{
$contracts = Contract::factory()->count(10)->make();
return response()->json([
'message' => 'good',
'contracts' => $contracts
], 200);
}
}
/**
* #OA\Schema(
* description="Contract model",
* type="object",
* title="Contract model"
* )
*/
class Contract extends Model
{
use HasFactory;
/**
* The unique identifier of a product in our catalog.
*
* #var integer
* #OA\Property(format="int64", example=1)
*/
public $id;
/**
* #var string
* #OA\Property(format="string", example="contract 001")
*/
public $contract_title;
}
Use type="array", (with "s) instead of type=array,
I know its late but
Try to use
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* type="array",
* #OA\Items(
* ref="#/components/schemas/Contract"
* ),
* )
* )
Insead of #OA\JsonContent
Certainly already asked but...
Having this entity
/**
* A form
*
* #ORM\Entity(repositoryClass=FormRepository::class)
*
* #ORM\Table(
* name="forms",
* options={"comment":"Table of the forms"},
* indexes={
* #ORM\Index(name="forms_idx_dofc", columns={"dateofcreation"}),
* #ORM\Index(name="forms_idx_dofu", columns={"dateofupdate"}),
* #ORM\Index(name="forms_idx_dofs", columns={"dateofsubmission"})
* }
* )
*
* #ApiResource(
* routePrefix="/",
* shortName="Forms",
* description="API Access : form Entity",
* collectionOperations={"GET"},
* itemOperations={"GET"},
* attributes={
* "normalization_context"={
* "groups"={
* "GET:FORM"
* }
* },
* "order"={
* "dateofsubmission",
* "dateofupdate",
* "dateofcreation"
* }
* }
* )
*
*/
class Form
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer", options={"comment":"Primary Key, Auto generated"})
*/
private $id;
/**
* #var datetime Date of creation of the form.
*
* #ORM\Column(type="datetime", options={"comment":"date of creation of the form"})
*
* #Assert\NotBlank(message="The date time when was created the form should not be blank")
* #Assert\DateTime(message="The data time when was created the form should be the type DateTime")
*
* #Groups({"GET:FORM"})
*
* #ApiFilter(OrderFilter::class, strategy="ASC")
*/
private $dateofcreation;
/**
* #var datetime Date of update of the form.
*
* #ORM\Column(type="datetime", options={"comment":"date of update of the form"})
*
* #Assert\NotBlank(message="The date time when was updated the form should not be blank")
* #Assert\DateTime(message="The data time when was updated the form should be the type DateTime")
*
* #Groups({"GET:FORM"})
*
* #ApiFilter(OrderFilter::class, strategy="ASC")
*/
private $dateofupdate;
/**
* #var person Person that has created the form.
*
* #ORM\ManyToOne(targetEntity=Person::class, inversedBy="forms")
* #ORM\JoinColumn(nullable=false)
*
* #Groups({"GET:FORM"})
*
* #ApiFilter(SearchFilter::class, properties={"createdBy.id":"exact","createdBy.givenname":"ipartial", "createdBy.familyname":"ipartial"})
* #ApiFilter(OrderFilter::class, strategy="ASC")
*/
private $createdBy;
...
I would like to have the possibility of having :
A base collectionOperations "GET" would return all the properties that have the #GROUP=GET:FORM
A alternate collectionOperations "GETDATES" would return all properties that have a #GROUP=GET:DATES
The operations being accessible (ideally) with different routes.
GET => # http://api/forms?createdBy.id=25 => All properties
GETDATES => http://api/formsLimited?createdBy.id=25 => only the dates
ps: I hope this is better for the readability.
Thanks to Grégoire Hébert(https://stackoverflow.com/users/4887997/gr%C3%A9goire-hebert) for the support (on Slack).
The solution is quite simple.
Create in the ApiResource() a collection operation with:
Method = GET
path (that will become a route)
the normalization context for the group to be applied to the wanted properties
It gives:
collectionOperations={"GET","GETLIMITED"={"method"="GET","path"="formslist","normalization_context"={"groups"="GET:LIMITED"}}},
I try to create a tree structure for a catalog of products.
A catalog can have multiple levels and levels can contain multiple products.
I manage to save my structure in database but when I want to edit it, I have this error :
Error : Missing value for primary key catalogCode on AppBundle\Entity\CatalogLevel
at OutOfBoundsException ::missingPrimaryKeyValue ('AppBundle\Entity\CatalogLevel', 'catalogCode')
in vendor\doctrine\common\lib\Doctrine\Common\Proxy\AbstractProxyFactory.php at line 125
when I do this in my CatalogController :
$form = $this->createForm(CatalogTreeType::class, $catalog);
But, just before that line, I verify if I get my levels correctly and it's looking like that's the case :
// Create an ArrayCollection of the current levels
$originalLevels = new ArrayCollection();
foreach ($catalog->getLevels() as $level) {
var_dump($level->getCatalogCode());
$originalLevels->add($level);
}
// returns
AppBundle\Controller\CatalogController.php:337:string 'TT-FTEST' (length=8)
AppBundle\Controller\CatalogController.php:337:string 'TT-FTEST' (length=8)
CatalogLevel entity has a composite key : levelId + catalogCode.
Considering the primary key catalogCode isn't empty, I don't understand this error...
Catalog Entity
/**
* #ORM\Table(name="catalogue")
* #ORM\Entity(repositoryClass="AppBundle\Entity\CatalogRepository")
* #UniqueEntity(fields="code", message="Catalog code already exists")
*/
class Catalog
{
/**
* #ORM\Column(name="Catalogue_Code", type="string", length=15)
* #ORM\Id
* #Assert\NotBlank()
* #Assert\Length(max=15, maxMessage="The code is too long ({{ limit }} characters max)")
*/
private $code;
/**
* #ORM\OneToMany(targetEntity="CatalogLevel", mappedBy="catalog", cascade={"persist", "remove"})
* #Assert\Valid
*/
private $levels;
/**
* Constructor
*/
public function __construct()
{
$this->levels = new ArrayCollection();
}
/**
* Get levels
*
* #return ArrayCollection
*/
public function getLevels()
{
return $this->levels;
}
/**
* Add level
*
* #param \AppBundle\Entity\CatalogLevel $level
*
* #return Catalog
*/
public function addLevel(\AppBundle\Entity\CatalogLevel $level)
{
$level->setCatalogCode($this->getCode());
$level->setCatalog($this);
if (!$this->getLevels()->contains($level)) {
$this->levels->add($level);
}
return $this;
}
/**
* Remove level
*
* #param \AppBundle\Entity\CatalogLevel $level
*/
public function removeLevel(\AppBundle\Entity\CatalogLevel $level)
{
$this->levels->removeElement($level);
}
}
CatalogLevel Entity
/**
* #ORM\Table(name="catalogue_niveau")
* #ORM\Entity(repositoryClass="AppBundle\Entity\CatalogLevelRepository")
*/
class CatalogLevel
{
/**
* #ORM\Column(name="Niveau_ID", type="string", length=15)
* #ORM\Id
*/
private $id;
/**
* #ORM\Column(name="Catalogue_Code", type="string", length=15)
* #ORM\Id
*/
private $catalogCode;
/**
* #ORM\ManyToOne(targetEntity="Catalog", inversedBy="levels")
* #ORM\JoinColumn(name="Catalogue_Code", referencedColumnName="Catalogue_Code")
*/
private $catalog;
/**
* Set id
*
* #param string $id
*
* #return CatalogLevel
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* #return string
*/
public function getId()
{
return $this->id;
}
/**
* Set catalogCode
*
* #param string $catalogCode
*
* #return CatalogLevel
*/
public function setCatalogCode($catalogCode)
{
$this->catalogCode = $catalogCode;
return $this;
}
/**
* Get catalogCode
*
* #return string
*/
public function getCatalogCode()
{
return $this->catalogCode;
}
}
I would like to remind you that this error occured on the editAction (it works very well on the addAction) when I display the pre-filled form.
Thanks for your help !
I think that is because you haven't autoincrement id in entity CatalogLevel. Try add to id this code:
#ORM\GeneratedValue(strategy="AUTO")
You have some problems in the way you've created you Entities. You should use auto generate strategy. Also the "#ORM\Id" annotation is the unique identifier.
Also, your "JoinColumn" is incorrect. You need to refer back to the "Catalog" Entity, and it's id (identifier). There is no need for 2 "#ORM\Id" entries in the class CatalogLevel.
So make these changes:
/**
* #ORM\Table(name="catalog")
* #ORM\Entity(repositoryClass="AppBundle\Entity\CatalogRepository")
*/
class Catalog
{
/**
* #ORM\Column(name="cat_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $cat_id;
/**
* #ORM\OneToMany(targetEntity="CatalogLevel", mappedBy="catalog", cascade={"persist", "remove"})
* #Assert\Valid
*/
private $levels;
...
/**
* #ORM\Table(name="catalog_level")
* #ORM\Entity(repositoryClass="AppBundle\Entity\CatalogLevelRepository")
*/
class CatalogLevel
{
/**
* #ORM\Column(name="cat_level_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $cat_level_id;
/**
* #ORM\ManyToOne(targetEntity="Catalog", inversedBy="levels")
* #ORM\JoinColumn(name="local_cat_id", referencedColumnName="cat_id")
*/
private $catalog;
...
i'm trying to retrive data from several tables to make a json, but i'm stuck for the table having UniqueConstraint on 2 keys.
Here's my QueryBuilder sofar :
$qb = $this->_em->createQueryBuilder()
->select('partial s.{id, activity}, partial a.{id, title}, partial p.{id, evaluationType}')
->from('Innova\PathBundle\Entity\Step', 's')
->leftJoin('s.activity', 'a') //join on Activity entity
->leftJoin('a.parameters', 'p') // join on ActivityParameters entity
->andWhere('s.path = 2')
;
but i want to also join on Evaluation entity, which is :
/**
* #ORM\Table(
* name="claro_activity_evaluation",
* uniqueConstraints={
* #ORM\UniqueConstraint(
* name="user_activity_unique_evaluation",
* columns={"user_id", "activity_parameters_id"}
* )
* }
* )
*/
class Evaluation
{
/**
* #ORM\ManyToOne(targetEntity="Claroline\CoreBundle\Entity\User")
* #ORM\JoinColumn(onDelete="CASCADE", nullable=false)
*/
protected $user;
/**
* #ORM\ManyToOne(targetEntity="Claroline\CoreBundle\Entity\Activity\ActivityParameters")
* #ORM\JoinColumn(name="activity_parameters_id", onDelete="CASCADE", nullable=false)
*/
protected $activityParameters;
/**
* #ORM\Column(name="attempts_count", type="integer", nullable=true)
*/
protected $attemptsCount;
}
the User entity :
/**
* #ORM\Table(name="claro_user")
* #ORM\Entity(repositoryClass="Claroline\CoreBundle\Repository\UserRepository")
*/
class User
{
/**
* #var integer
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="first_name", length=50)
* #Assert\NotBlank()
*/
protected $firstName;
}
The ActivityParameters entity
/**
* #ORM\Entity
* #ORM\Table(name="claro_activity_parameters")
*/
class ActivityParameters
{
/**
* #var integer
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var \Claroline\CoreBundle\Entity\Resource\Activity
*
* #ORM\OneToOne(
* targetEntity="Claroline\CoreBundle\Entity\Resource\Activity",
* mappedBy="parameters"
* )
* #ORM\JoinColumn(name="activity_id", onDelete="CASCADE", nullable=true)
*/
protected $activity;
/**
* #var string
*
* #ORM\Column(name="evaluation_type", nullable=true)
*/
protected $evaluationType;
/**
* #return string
*/
public function getEvaluationType()
{
return $this->evaluationType;
}
}
the Activity entity
/**
* #ORM\Table(name="claro_activity")
*/
class Activity
{
/**
* #var string
* #ORM\Column(length=255, nullable=true)
*/
protected $title;
/**
* #ORM\OneToOne(
* targetEntity="Claroline\CoreBundle\Entity\Activity\ActivityParameters",
* inversedBy="activity",
* cascade={"persist"}
* )
* #ORM\JoinColumn(name="parameters_id", onDelete="cascade", nullable=true)
*/
protected $parameters;
/**
* #return string
*/
public function getTitle()
{
return $this->title;
}
}
I have no clue how to modify this querybuilder to retrieve also hte data from Evaluation entity. I want something like :
$qb = $this->_em->createQueryBuilder()
->select('partial s.{id, activity}, partial a.{id, title}, partial p.{id, evaluationType}, e')
->from('Innova\PathBundle\Entity\Step', 's')
->leftJoin('s.activity', 'a') //join on Activity entity
->leftJoin('a.parameters', 'p') // join on ActivityParameters entity
->andWhere('s.path = 2')
->leftJoin('?i dont know what?', 'e') // join on Evaluation entity
->andWhere('e.user = 3') //data for a specific user
;
Thank you for any help
I "seem" to have found a nearly working solution, reading this topic : i had to make a subquery :
$qb->select('e, partial p.{id, evaluationType}, partial a.{id, title}')
->from('Claroline\CoreBundle\Entity\Activity\Evaluation', 'e')
->leftJoin('e.activityParameters', 'p')
->leftJoin('p.activity', 'a')
->where(
$qb->expr()->in( //needs a subquery
'a.id',
$subq->select('a2.id')
->from('Innova\PathBundle\Entity\Step', 's')
->leftJoin(
's.activity',
'a2',
\Doctrine\ORM\Query\Expr\Join::WITH,
$subq->expr()->eq('s.path', '?1') //can't do a andWhere('s.path = :path'))
)
->getDQL() //needs a dql, not a querybuilder for the main query
)
)
->andWhere($qb->expr()->eq('e.user', '?2')) //can't do a andWhere('e.user = :user'))
->setParameter(1, $pid)
->setParameter(2, $uid)
;
I just would also like to retrieve the Step entity data (id, ...) in the query result. I can't add 's' to the main select : i have Error: 's' is used outside the scope of its declaration.