As i am new to symfony framework, for my client symfony website doing the maintenance. i have tried to insert a record into a new table, which was actually a sub table of a already existing table.
But i am not able to write the insert query in this. which shows the error only.
Please check and provide the solutions for the below code,
public function executeUpdatednc(sfWebRequest $request)
{
$patient_id = $_REQUEST['pid'];
$q = Doctrine_Query::create()
->update('patient')
->set('isadmindnc', '?', 1)
->where('id = ?', $patient_id)
->execute();
$datetime = date("Y-m-d H:i:s");
##### Here i need to write the sub query to insert into the new table, Please suggest #####
//$rsm = new ResultSetMapping();
//$query = $this->_em->createNativeQuery('INSERT INTO patient_phone SET ph_pid = ?', $patient_id);
//$query->setParameter(1, $items);
//$result = $query->getResult();
}
For me, simple way to resolve this problem (for update):
$patient = Doctrine_Core::getTable('patient')->findOneById($patient_id);
$patient->setIsadmindnc(1);
$patient->save();
For insert:
$patient = new Patient();
$patient->setIsadmindnc(1);
$patient->save();
Related
Hove to create custom Repository function who query by json field. I have params column in my database who look like this:
"params": {
"product": "stopper",
"itemIdentifier": ""
}
I want to query record by product value. In this case stopper term.
You can achieve this with a classic example :
In your repository :
For one result
public function findOneProduct($value): ?Params
{
return $this->createQueryBuilder('p')
->andWhere('p.product = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
For multiple result
public function findParamsByProduct($value): ?Params
{
return $this->createQueryBuilder('p')
->andWhere('p.product = :val')
->setParameter('val', $value)
->orderBy(/*some field */)
->setMaxResults(/*if needed*/)
->getQuery()
->getResults()
;
}
In your controller:
$stoppers = $entityManager->getRepository(Params::class)->findParamsByProduct('stopper');
If I understood your question correctly, you have a table with a column named params. And inside this mysql column, you store JSON text.
And then you want to query that table and filter by looking into the JSON in your column.
This can be a bit tedious and was also highly discouraged in the past (prior to the JSON Type in Mysql 5.7.8).
Best practices would be to have a NoSQL DB such as MongoDB which is actual JSON stored in a collection(table).
Anyways, there is a solution for you.
Taking into account #AppyGG explained how to make a custom repository function.
First of all, we have to make a query using pure SQL.
It can be done two ways:
1.Return arrays containing your data.
$conn = $this->getEntityManager()->getConnection();
$sql = '
SELECT * FROM product p
WHERE p.price > :price
ORDER BY p.price ASC
';
$stmt = $conn->prepare($sql);
$stmt->execute(['price' => $price]);
// returns an array of arrays (i.e. a raw data set)
return $stmt->fetchAll();
2.Return hydrated Entities
use Doctrine\ORM\Query\ResultSetMappingBuilder;
$rsm = new ResultSetMappingBuilder($entityManager);
$rsm->addRootEntityFromClassMetadata('MyProject\Product', 'p');
$sql = '
SELECT * FROM product p
WHERE p.price > :price
ORDER BY p.price ASC
';
$nql = $this->_em->createNativeQuery( $sql, $rsm );
$nql->setParameter('price', $price);
//Return loaded entities
return $nql->getResult();
Now, knowing how to make make a MySQL query with doctrine, we want to select results filtered in JSON data.
I'm am referencing this beautiful stackoverflow which explains it all:
How to search JSON data in MySQL?
The easiest solution proposed in there requires at least MySQL 5.7.8
Your MySQL query would be as follow:
//With $entity->getParams() == '{"params": {"product":"stopper", "itemIdentifier":""}}'
$conn = $this->getEntityManager()->getConnection();
$sql = '
SELECT * FROM Entity e
WHERE JSON_EXTRACT(e.params, "$.params.product") = :product
';
//Or Like this if the column is of Type JSON in MySQL(Not doctrine, yes check MySQL).
$sql = '
SELECT * FROM Entity e
WHERE e.params->"$.params.product" = :product
';
$stmt = $conn->prepare($sql);
$statement->bindValue("product","stopper");
$stmt->execute();
return $statement->fetchAll();
Hope this helps!
P.S: Note that my example uses a column named 'params' with a Json containing also a named attribute 'params', this can be confusing. The intended purpose is to show how to do multiple level filtering.
I want to know that How I can customize getExportFields function in Sonata Admin extend Class.
My Problem is my class fields createdAt type is datetime but I want when admin download this class data then in CSV or XLS file createdAt format DATE, not a datetime.
I want show data in CSV or XLS file through join other tables.
I searched many times on google but nothing found.
This one I try for join but I am not success-
public function getExportFields()
{
$em = $this->modelManager->getEntityManager('ABC\FroBundle\Entity\Model');
$conn = $em->getConnection();
$query = "SELECT mp.id, mp.userModel, u.email, m.model_name
FROM model_p mp
LEFT JOIN user u ON mp.user_id = u.id
LEFT JOIN m_model m ON mp.model_id = m.id limit 1";
$statement = $conn->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
foreach($results as $res){
$reets = $res;
}
$fieldsArray = $reets;
}
Any one know this type issue please help.
I asked this question on Github:- https://github.com/sonata-project/SonataAdminBundle/issues/2221
Thanks!
Maybe the solution by #Petr Slavicek can help:
Original question: symfony2 - SonataAdminBundle Exporter issue with mapped entities - Stack Overflow
Try to use the Doctrine DateTime formatter on the object e.g.:
if ($value instanceof \DateTime) {
$value = $this->dateFormater->format('d.m.Y');
}
I want to get the total results for a query using elastica for symfony2
what I did :
$u = $this->container->get('fos_elastica.finder.documents_index.documents');
$maxItems=10;
$query = new \Elastica\Query\Bool();
$elasticaQuery = new \Elastica\Query\QueryString($key_words.'~');
$elasticaQuery->setFuzzyPrefixLength(3);
$query->addMust($elasticaQuery);
try {
$q = new \Elastica\Query();
$q->setQuery($query);
$q->setFrom(($page - 1) * $maxItems);
}
catch (Exception $e) {
}
$data = $u->find($q);
$data is always 10 documents but this is not the problem , the problem is how to get the total hits so I can use them in Pagination :)
The Elastica\ResultSet class has a method called getTotalHits() so you can do something like this after the search and get the full record count for totals/pagination/etc:
$hits = $resultSet->getTotalHits();
See source code here: Elastica ResultSet Class.
As an aside, the Elastica source code is incredibly well-structured and easy to read which more than makes up for it's lack of documentation. Well worth reading both the source and the unit tests if you get stuck.
I have a simple query which selects entities and uses limit statement. I am using Doctrine NativeQuery because I have FIELD() function in sql query, and I need a collection of objects as a result.
That query works.
However I need also a total number of records, so I use SQL_CALC_FOUND_ROWS in the first query. After the first gets the result I create another ResultSetMapping, another $nativeQuery, execute SELECT FOUND_ROWS() AS found_rows and I keep getting total number of '1'.
$rsm = new ResultSetMapping();
$rsm->addEntityResult('\\MyCompany\\Administration\\Domain\\Model\\Applicant\\Applicant', 'a');
$rsm->addFieldResult('a', 'first_name', 'firstName');
$rsm->addFieldResult('a', 'last_name', 'lastName');
$query = $this->em->createNativeQuery('SELECT SQL_CALC_FOUND_ROWS * FROM recruitment_applicant ORDER BY FIELD(id,5,15,8,17,2,1,16,9,7,11,6,10,12,13,14,18)', $rsm);
$result = $query->getResult(); // this result is ok
$sqlCountRows = "SELECT FOUND_ROWS() AS found_rows";
$countRowsRsm = new ResultSetMapping();
$countRowsRsm->addScalarResult('found_rows', 'foundRows');
$countRowsQuery = $this->em->createNativeQuery($sqlCountRows,$countRowsRsm);
$rowsCount = $countRowsQuery->getResult();
$total = $rowsCount[0]['foundRows']; // result is '1' when it should be '16'
I used this example.
You don't have to use native query. FIELD() is really very easy to implement as a custom DQL function:
Read DQL User Defined Functions and How to Register Custom DQL Functions on Doctrine/Symfony documentation.
FIELD() implementation:
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
class Field extends FunctionNode
{
private $field = null;
private $values = array();
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->field = $parser->arithmeticPrimary();
while (count($this->values) < 1 || $parser->getLexer()->lookahead['type'] !== Lexer::T_CLOSE_PARENTHESIS) {
$parser->match(Lexer::T_COMMA);
$this->values[] = $parser->arithmeticPrimary();
}
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker)
{
$values = array();
foreach ($this->values as $value) {
$values[] = $value->dispatch($sqlWalker);
}
return sprintf('FIELD(%s, %s)', $this->field->dispatch($sqlWalker), implode(', ', $values));
}
}
You won't event need a count query. However, if you'd need COUNT(*) query you can easily clone your original query and use CountWalker to create count query from select query.
I found out what might be a cause of the problem: Symfony2 profiler, queries section, shows total of 22 queries executed. My first query gets run third in a row and my second query, the one to return the number of rows gets executed 13th.
SQL_CALC_FOUND_ROWS works if SELECT FOUND_ROWS() is run immediately after the first query.
I have a table in my database called gsm_tariff. Basically I just want to run a simple select query
"SELECT * FROM {gsm_tariff} WHERE Country='Afghanistan'"
and store the results in an array. Can anyone help me with how to do this please? I know where to put the code and everything; I just need the code to do the query and store the results in an array.
$array = array();
$result = db_query('SELECT * FROM {gsm_tariff} WHERE Country = "%s"', 'Afghanistan');
while ($record = db_fetch_object($result)) {
$array[] = $record->(data to reference);
}
Note that I don't know the field you want to reference given the question, but it would be in the $record object.