Let's say I have two entities Bus and People with a relation OneToMany between them.
Bus can hold a maximum of 10 persons.
How to create a constraint to control this?
For example:
* #MyAssert\ParentMaxChild(max=10)
* #ORM\ManyToOne(targetEntity="Webface\CharacterBundle\Entity\Bus", inversedBy="wac")
* #ORM\JoinColumn(name="bus_id", referencedColumnName="id", nullable=false)
private $bus;
Use the Count constraint.
In your Bus class, add the constraint in the Person annotation:
/**
* ... Rest of the annotation ...
* #Assert\Count(
* max = "10",
* maxMessage = "Bus can hold a maximum of 10 persons."
* )
*/
protected $persons;
Note that you can specify a min parameter and the according message.
Related
In our scenario we have a (multivalued) category field on JCR:node and we want to query all nodes that do not have a current selection. In the JCR viewer the fields value is [] but I can't find any query to select nodes with this condition. We have tries:
SELECT * FROM [mgnl:page] as p WHERE p.[categories]=''
or
SELECT * FROM [mgnl:page] as p WHERE p.[categories]=[]
or
SELECT * FROM [mgnl:page] as p WHERE p.[categories] is null
But they aren't working or don't select the proper result. How can we write a query selecting these nodes?
From the JSR 283:
5.10.3 Value Length
The length of a value in a single-value property, as defined in ยง3.6.7 Length of a Value, is returned by long Property.getLength()
Similarly, the method long[] Property.getLengths() is used to get an array of the lengths of all the values of a multi-value property.
From the JavaDocs:
/**
* Returns an array holding the lengths of the values of this (multi-value)
* property in bytes where each is individually calculated as described in
* {#link #getLength()}.
* <p>
* Returns a <code>-1</code> in the appropriate position if the
* implementation cannot determine the length of a value.
*
* #return an array of lengths
* #throws ValueFormatException if this property is single-valued.
* #throws RepositoryException if another error occurs.
*/
public long[] getLengths() throws ValueFormatException, RepositoryException;
Unfortunately, this does not make it clear what the result of LENGTH([multivaluedProperty)] is in a SQL2 query.
Though, after some manual testing, it seems that the LENGTH operand returns some number smaller than 0. Therefore, you could try
select * from [nt:base] where LENGTH([multivaluedProperty]) < 0
Let me know whether this works for you :)
I'm trying to make a many to many join with a Doctrine findBy()
$articles = $entityManager->getRepository(Articles::class)
->findBy(['rubriquesrubriques'=>$id],['idarticles'=>"ASC"]);
But I get
An exception occurred while executing
'SELECT t0.idarticles AS idarticles_1,
t0.thetitle AS thetitle_2, t0.theslug AS theslug_3, t0.thedescription AS
thedescription_4, t0.thedate AS thedate_5, t0.users_idusers AS users_idusers_6
FROM articles t0 WHERE
articles_has_rubriques.rubriques_idrubriques = ?
ORDER BY t0.idarticles ASC' with params ["2"]:
SQLSTATE[42S22]: Column not found: 1054 Champ
'articles_has_rubriques.rubriques_idrubriques' inconnu dans where clause
The column articles_has_rubriques.rubriques_idrubriques exists in my DB,
but I don't see the INNER JOIN !
When I make my many to many with a simple Find():
$articles = $entityManager->getRepository(Articles::class)->find($id);
The query is correct!
SELECT t0.idrubriques AS idrubriques_1,
t0.thertitle AS thertitle_2
FROM
rubriques t0
INNER JOIN articles_has_rubriques ON t0.idrubriques =
articles_has_rubriques.rubriques_idrubriques
WHERE articles_has_rubriques.articles_idarticles = ?
is it impossible to perform my many2many query with a findBy in the 4.1.6 version of Symfony???
This is my ORM relation:
In entity Rubriques.php:
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Articles", mappedBy="rubriquesrubriques")
*/
private $articlesarticles;
In entity Articles.php
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Rubriques", inversedBy="articlesarticles")
* #ORM\JoinTable(name="articles_has_rubriques",
* joinColumns={
* #ORM\JoinColumn(name="articles_idarticles", referencedColumnName="idarticles")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="rubriques_idrubriques", referencedColumnName="idrubriques")
* }
* )
*/
private $rubriquesrubriques;
Thank you so much
My question was stupid :
I'have an easy way to do that:
$rubriqueActu = $entityManager->getRepository(Rubriques::class)->find($id);
$articles = $rubriqueActu->getArticlesarticles();
SQL:
SELECT t0.idarticles AS idarticles_1, t0.thetitle AS thetitle_2,
t0.theslug AS theslug_3, t0.thedescription AS thedescription_4,
t0.thedate AS thedate_5, t0.users_idusers AS users_idusers_6
FROM articles t0 INNER JOIN articles_has_rubriques
ON t0.idarticles = articles_has_rubriques.articles_idarticles
WHERE articles_has_rubriques.rubriques_idrubriques = ?
I have this entity:
class TruckOrderPud {
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="Pud")
* #ORM\JoinColumn(name="pud_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $pudId;
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="TruckOrder")
* #ORM\JoinColumn(name="truck_order_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $truckOrderId;
/**
* #ORM\Column(name="package_count", type="integer", options={"unsigned"=true}, nullable=true)
*/
protected $packageCount;
/**
* #ORM\Column(name="package_weight", type="integer", options={"unsigned"=true}, nullable=true)
*/
protected $packageWeight;
}
I am needing get only single column pudId from this entity by truckOrderId parameter.
I am try:
$result = $this->_em->createQuery('SELECT top.pudId FROM AppTruckingBundle:TruckOrderPud top WHERE top.truckOrderId = ?1')
->setParameter(1, $truckOrderId)
->getSQL();`
Then I have error:
"[Semantical Error] line 0, col 11 near 'pudId FROM AppTruckingBundle:TruckOrderPud': Error: Invalid PathExpression. Must be a StateFieldPathExpression."
If i change query from 'SELECT top.pudId...' on 'SELECT top...' is it all OK.
I am also try:
$qb = $this->_em->createQueryBuilder();
$qb->select('top.pudId')
->from('AppTruckingBundle:TruckOrderPud', 'top')
->where($qb->expr()->eq('top.truckOrderId', $truckOrderId));`
In this case I am getting identical error. If i change $qb->select('top.pudId') on $qb->select('top') is it all OK.
Thanks for help!
PudId is a foreign key that refers to Pud, so you have to refer to Pud. Try this
$qb->select('IDENTITY(top.pud) PudId')
->from('AppTruckingBundle:TruckOrderPud', 'top')
->where($qb->expr()->eq('top.truckOrderId', $truckOrderId));`
Try to remove the 1 from the ?1 and leave only ?:
$result = $this->_em->createQuery('SELECT top.pudId FROM AppTruckingBundle:TruckOrderPud top WHERE top.truckOrderId = ?')
->setParameter(1, $truckOrderId)
->getSQL();
Doctrine does the parameter positioning by itself (first param on the first question mark spot). Read here for details.
I have database table with 7 rows, I'am trying to fetch those rows with findAll function
$machine_current_counter_repo = $this->getDoctrine()->getRepository('DummyMonitorBundle:MachineCurrentCounter');
$counters = $machine_current_counter_repo->findAll();
The result is 7 rows, but all rows contain data from the first row.
Here is database table entity.
And table structure:
`machine_current_counter` (
`machine_id` tinyint(3) unsigned NOT NULL,
`counter_value` int(10) unsigned NOT NULL,
`time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`machine_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
What could cause this problem?
Ps. Entity is generated from database so by default first column setup was this (not sure why type was "boolean", but I changes it to integer, still that didn't solved the problem):
/**
* #var boolean
*
* #ORM\Column(name="machine_id", type="boolean")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $machineId;
#ORM\Id means values of this field MUST be unique. With the boolean type they can be unique only in 2 or less row (because boolean has only 2 values - 0 and 1).
I think you have logical mistake, and must simply change type of field to integer. Like that:
/**
* #var integer
*
* #ORM\Column(name="machine_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $machineId;
Then update your schema by ./app/console doctrine:schema:update then recreate data into table.
I need to have my database schema information stored in the database.
I already have a table called db_entity which stores the entity name, namespace and other options.
Related to this table I need to have a table entity_attributes which will have the entity_id,attribute_name,attribute_type,required etc.
Creating the schema structure is easy but inserting all the fields from all my entites in the db would be a tedious work.
Is there any way I can create a script that will parse all my entities annotations, allowing me to create all the fields into my database table?
The best would be to write a similar command to doctrine:schema:update that would update my table schema.
Thank you.
The doctrine metadata class http://www.doctrine-project.org/api/orm/2.2/source-class-Doctrine.ORM.Mapping.ClassMetadataInfo.html contains a public property that could be exactly what you need:
222: /**
223: * READ-ONLY: The field mappings of the class.
224: * Keys are field names and values are mapping definitions.
225: *
226: * The mapping definition array has the following values:
227: *
228: * - <b>fieldName</b> (string)
229: * The name of the field in the Entity.
230: *
231: * - <b>type</b> (string)
232: * The type name of the mapped field. Can be one of Doctrine's mapping types
233: * or a custom mapping type.
234: *
235: * - <b>columnName</b> (string, optional)
236: * The column name. Optional. Defaults to the field name.
237: *
238: * - <b>length</b> (integer, optional)
239: * The database length of the column. Optional. Default value taken from
240: * the type.
241: *
242: * - <b>id</b> (boolean, optional)
243: * Marks the field as the primary key of the entity. Multiple fields of an
244: * entity can have the id attribute, forming a composite key.
245: *
246: * - <b>nullable</b> (boolean, optional)
247: * Whether the column is nullable. Defaults to FALSE.
248: *
249: * - <b>columnDefinition</b> (string, optional, schema-only)
250: * The SQL fragment that is used when generating the DDL for the column.
251: *
252: * - <b>precision</b> (integer, optional, schema-only)
253: * The precision of a decimal column. Only valid if the column type is decimal.
254: *
255: * - <b>scale</b> (integer, optional, schema-only)
256: * The scale of a decimal column. Only valid if the column type is decimal.
257: *
258: * - <b>unique (string, optional, schema-only)</b>
259: * Whether a unique constraint should be generated for the column.
260: *
261: * #var array
262: */
263: public $fieldMappings = array();