Symfony 3/Doctrine: Sorting by non-persistent columns - doctrine

I have two Models that are related to each other:
class Product
{
//...
/**
* #var Collection<Key>
* One Product has Many Keys.
* #ORM\OneToMany(targetEntity="Key", mappedBy="product")
*/
private $keys;
public function getKeyNumber()
{
return count($this->keys);
}
//...
}
class Key
{
//...
/**
* #var Product
*
* Many Keys have One Product.
* #ORM\ManyToOne(targetEntity="Product", inversedBy="keys")
* #ORM\JoinColumn(referencedColumnName="id")
*/
private $product;
/**
* #var int
* #ORM\Column(type="integer")
*/
private $product_id;
//...
}
I am able to get the number of Keys with Product::getKeyNumber(). Now I'd like to use this value for sorting in the query.
I've tried something like that (DQL Query):
SELECT a, COUNT(a.keys) AS keyNumber FROM AppBundle\Entity\Product a ORDER BY keyNumber ASC;
which returns:
[Semantical Error] line 0, col 18 near 'keys) AS keyNumber': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.
When I try:
SELECT a FROM AppBundle\Entity\Product a ORDER BY count(a.keys) ASC
it says:
[Syntax Error] line 0, col 50: Error: Expected known function, got 'count'
Any ideas? :)
Thanks.

You can try doing something like this (just an idea, not a verified code)
SELECT a, COUNT(b.id) AS keyNumber FROM AppBundle:Product a JOIN a.keys b ORDER BY keyNumber ASC;
As soon as COUNT() expects single value field you can explicitly join the keys table and count on something in it (I assume it has ID or you can use whatever is there).

I wonder if it has to do with composite keys? I read something about that. I don't know what your key identifier is, but I show a.id below. Can you try this:
SELECT IDENTITY(a.id), a, COUNT(a.keys) AS keyNumber FROM AppBundle:Product a ORDER BY keyNumber ASC
Note, I've reduced AppBundle\Entity\Product to simply AppBundle:Product and got rid of the semicolon at the end.
Let me know if that works, it may not.

Related

How to make query in model with 2 parameters

I need make a query with 2 parameters in model on codeigniter 4.
Is this possible?
This is the model:
public function obtenerProyectoId($id_user,$id_project)
{
$proyectos = $this->db->query(" SELECT * FROM proyectos INNER JOIN empresa ON proyectos.id_usuario=$id_user and proyectos.id_proyecto=id_project");
return $proyectos->getResultArray();
}
in mysql this query is correct, but in CI4 it shows an error:
Too few arguments to function App\Models\Proyectos::obtenerProyecto(),
1 passed in
C:\xampp\htdocs\plataformaknowmad\app\Controllers\verProyectos.php on
line 25 and exactly 2 expected
Yes, it is possible to make a query with multiple params.
//if second param is optional
public function obtenerProyectoId($id_user,$id_project="")
In query $ is missing from id_project
$this->db->query("SELECT * FROM proyectos INNER JOIN empresa ON proyectos.id_usuario=$id_user and proyectos.id_proyecto=$id_project");
May be you did not pass second parameter($id_project) in controller:
verProyectos.php on line 25 and exactly 2 expected

Arithmetic operations in select with CodeIgniter

I´m triying to do an arithmetic operation but i always get error.
This is the query:
public function getAllModifiers($condition)
{
$this->db->select('DM.id AS modifier_id, DM.name, minimum, maximum');
$this->db->select('DMI.id AS item_id, DMI.name AS item_name, `DMI.price * 1.1` AS item_price');
$this->db->from('dishes_modifiers DM');
$this->db->join('dishes_modifiers_items DMI', 'DMI.modifier_id = DM.id', 'left');
$this->db->where($condition);
return $this->db->get()->result();
}
How can i get the item_price * 1.1?
Thanks.
The backticks are used to escape object names (e.g., columns names). Any mathematical operation should be outside this escaping:
$this->db->select(`DMI.price` * 1.1 AS item_price');
# Here -----------^---------^
Check this:
$this->db->where($condition);
This one not checking the data with the database values.
You can use this in where condition
(DMI.price *1.1) > DMI.price *1.1

CodeIgniter escaping table

I know CodeIgniter automatically escapes values being sent to say an insert or update query e.g. $bar, but will it also escape $table if table is being received from say a post or get? I couldn't find any documentation on that.
$this->db->insert($table, array('foo' => $bar));
if you look at CodeIgniter's 2.x system/database/drivers/DB_driver.php near line 902
or
at CodeIgniters 3.x system/database/DB_driver near line 1365
you'll find a function called insert_string() which looks like this:
/**
* Generate an insert string
*
* #access public
* #param string the table upon which the query will be performed
* #param array an associative array data of key/values
* #return string
*/
function insert_string($table, $data)
{
$fields = array();
$values = array();
foreach ($data as $key => $val)
{
$fields[] = $this->_escape_identifiers($key);
$values[] = $this->escape($val);
}
return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
}
then follow-up function _protect_identifiers() near line 1246 (CI 2.x) or near line 1729 (CI 3.0) which says:
* Since the column name can include up to four segments (host, DB, table, column)
* or also have an alias prefix, we need to do a bit of work to figure this out and
* insert the table prefix (if it exists) in the proper position, and escape only
* the correct identifiers.
so the answer is YES.
in case of doubt you can always use this: echo ($this->db->last_query());die(); which prints out your last query performed what could look like this:
INSERT INTO `googlemaps_marker` (`descr`, `Lat`, `Lng`, `pretty_url`, `ID`, `zone_ID`, `kind`, `author_id`, `author`, `date_updated`) VALUES ('sasasasdas', '41.27780646738183', '-7.437744140625', 'sasasasdas', 4, 4, 1, '1', 'Admini Istrator', '2017-07-15 18:20:40')

Need array instead of object in laravel using raw Query like DB::select("SELECT * FROM table");

In laravel when i use DB::select("SELECT * FROM table");
It return a object,but i need a array.
So how can i get a array instead of object?
example:
$data = DB::select("SELECT * FROM table");
var_dump($data);
Please Try this one.
\Illuminate\Support\Facades\DB::setFetchMode(PDO::FETCH_ASSOC);
$values=\Illuminate\Support\Facades\DB::select("select * from your_table");
\Illuminate\Support\Facades\DB::setFetchMode(PDO::FETCH_CLASS);
var_dump($values);
It actually returns an array of objects. To make an individual object to be an array just cast it. For example: (array)$data[0]

TYPO3: Calculate Cache identifier hash value?

In TYPO3 I want to remove a single page from the cache table with some GET values. I haven't found an extension, that will handle that or a TYPO3 method.
Is there a function, that I can hand over a URL or similar, that produces the cache hash identifier or removes the specific data from the caching tables?
If not, does anybody know, what the algorithm is, that calculates the hash identifier or in which file I might find it?
So any help will be appreciated.
My TYPO3 version: 4.5.x
You can create a function which clear the cache of a specified page, following code is needed:
TYPO3 6.0
public function clearCache($cacheCmd) {
/** #var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
$tce = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance("TYPO3\\CMS\\Core\\DataHandling\\DataHandler");
$tce->stripslashes_values = 0;
$tce->start(array(), array());
switch($cacheCmd) {
case 'pages':
case 'all':
$tce->admin = 1;
}
$tce->clear_cacheCmd($cacheCmd);
unset($tce);
}
TYPO3 4.x
public function clearCache($cacheCmd) {
/** #var $tce t3lib_TCEmain */
$tce = t3lib_div::makeInstance("t3lib_TCEmain");
$tce->stripslashes_values = 0;
$tce->start(array(), array());
switch($cacheCmd) {
case 'pages':
case 'all':
$tce->admin = 1;
}
$tce->clear_cacheCmd($cacheCmd);
unset($tce);
}
And $cacheCmd can have following values:
/typo3/sysext/core/Classes/DataHandling/DataHandler.php:clear_cacheCmd (> 6.0) or /t3lib/class.t3lib_tcemain.php (4.x)
/**
* Clears the cache based on the command $cacheCmd.
*
* $cacheCmd='pages': Clears cache for all pages. Requires admin-flag to
* be set for BE_USER.
*
* $cacheCmd='all': Clears all cache_tables. This is necessary if
* templates are updated. Requires admin-flag to be set for BE_USER.
*
* $cacheCmd=[integer]: Clears cache for the page pointed to by $cacheCmd
* (an integer).
*
* $cacheCmd='cacheTag:[string]': Flush page and pagesection cache by given tag
*
* $cacheCmd='cacheId:[string]': Removes cache identifier from page and page section cache
*
* Can call a list of post processing functions as defined in
* $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc']
* (numeric array with values being the function references, called by
* \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction()).
*
* Note: The following cache_* are intentionally not cleared by
* $cacheCmd='all':
*
* - cache_md5params: RDCT redirects.
* - cache_imagesizes: Clearing this table would cause a lot of unneeded
* Imagemagick calls because the size informations have
* to be fetched again after clearing.
*
* #param string $cacheCmd The cache command, see above description
* #return void
*/
Call this with a userFunc if a given parameter is set in typoscript or create a simple extension by your own.
It's like this:
You need a proper TSFE object $GLOBALS['TSFE']
then you need the encryption key from the localconf $TYPO3_CONF_VARS['SYS']['encryptionKey']
and the URL parameters e.g. `tx_ttnews[tt_news]
then these steps
create an (sorted) array with the encryption key and the url parameters
Hand over this array to the property cHash_array of the TSFE object
Get the cHash value from the TSFE's getHash method
$arr = array(
'encryptionKey' => $TYPO3_CONF_VARS['SYS']['encryptionKey'],
'tx_ttnews[tt_news]' => $newsid,
// ...
)
ksort($array);
$GLOBALS['TSFE']->cHash_array = $array;
$chash = $GLOBALS['TSFE']->getHash();

Resources