TYPO3 8.7.13 - MariaDB QueryBuilder FULLTEXT - php

SELECT name
FROM tx_snippethighlightsyntax_domain_model_snippets
WHERE (MATCH(name, description, code, comment) AGAINST ('css'));
This query works in phpMyAdmin with MariaDB. Now my "problem" is to adapt this in TYPO3 with QueryBuilder. I don't see any MATCH or AGAINST operator.
So far, my function start with this:
private $tx = 'tx_snippethighlightsyntax_domain_model_snippets';
public function ftsSearch()
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$ftsQueryBuilder = $connectionPool->getQueryBuilderForTable($this->tx);
$fts = $ftsQueryBuilder
->select($this->tx . '.name')
->from($this->tx)
->where($ftsQueryBuilder->expr()->eq(
MAGIC HAPPENS HERE ?
)
->execute()
->fetchAll();
return $fts;
}

The extension Indexed Search in the TYPO3 core uses MATCH and AGAINST in queries.
The following code taken from IndexSearchRepository should help you building up your query
$searchBoolean = '';
if ($searchData['searchBoolean']) {
$searchBoolean = ' IN BOOLEAN MODE';
}
$queryBuilder->andWhere(
'MATCH (' . $queryBuilder->quoteIdentifier($searchData['fulltextIndex']) . ')'
. ' AGAINST (' . $queryBuilder->createNamedParameter($searchData['searchString'])
. $searchBoolean
. ')'
);

private $tx = 'tx_snippethighlightsyntax_domain_model_snippets';
public function ftsSearch()
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$ftsQueryBuilder = $connectionPool->getQueryBuilderForTable($this->tx);
$fts = $ftsQueryBuilder
->select($this->tx . '.name')
->from($this->tx)
->where('MATCH('
. $this->tx .'.name,'
. $this->tx .'.description,'
. $this->tx .'.code,'
. $this->tx .'.comment)'
. ' AGAINST(' . $ftsQueryBuilder->createNamedParameter('put_search_here')
. ')')
->execute()
->fetchAll();
return $fts;
}
This one works for me. Thank you !

Related

laravel mysql to query builder

i'm relatively new to laravel and i'm having issues when trying to convert this function to laravel's query builder. This is the function i've been given which also runs a python script to decrypt the database.
Using the documentation from laravel.com you can do something like this:
function call($unitId)
{
$pfContact = DB::table('PFContact')
->where('UnitID', $unitId)
->latest() // Order by created_at
->first([ // Only retrieve these columns
'Send',
'Receive',
'Core',
'lock'
]);
$pfReadings = DB::table('PFReadings')
->get();
$rowCount = $pfReadings->count();
foreach ($pfReadings as $i => $reading) {
echo $i < count($reading) / $rowCount;
foreach ($reading as $column => $value) {
echo shell_exec(
'python3 enc.py ' . $value
. ' ' . $pfContact->Send
. ' ' . $pfContact->Receive
. ' ' . $pfContact->Core
. ' ' . $pfContact->lock . ' '
. $unitId . ' l'
) . '~';
}
echo ';';
}
}
And although I do not know what arguments this pyhton script needs you should really think this through. Why would you use PHP for this and not just handle everything from the python (or php) side because this looks over complicated to me.

Laravel 5.4 from 5.3 : Error getOtherKey()

I was getting the relationship as in laravel 5.3 and was working fine:
//execute the relation of the given model
$data = $model->{$info["relation"]}();
// get the type of the relation
$class = get_class($data);
$dataType = explode("\\", $class);
$relationType = end($dataType);
$options["columns"][$key]["relationType"] = $relationType;
// if its a simple belongs-to statement
if($relationType == "BelongsTo") {
// get all belongs-to query info
$otherTable = $data->getRelated()->getTable();
$foreignKey = $data->getQualifiedForeignKey();
$otherKey = $data->getOtherKey();
// manually join using it
$retrievedRecords->leftJoin($otherTable . ' as ' . $info["relation"], $info["relation"] . '.' . $otherKey, '=', $foreignKey);
} else if($relationType == "HasMany" || $relationType == "HasOne") {
// get all has-many query info
$otherTable = $data->getRelated()->getTable();
$foreignKey = $data->getPlainForeignKey();
$parentKey = $data->getQualifiedParentKeyName();
// manually join using it
$retrievedRecords->leftJoin($otherTable . ' as ' . $info["relation"], $info["relation"] . '.' . $foreignKey, '=', $parentKey);
}
Now i downloaded fresh laravel 5.4 and it gives me error :
Call to undefined method Illuminate\Database\Query\Builder::getOtherKey()
As the getOtherKey() exists in the above code in if() section.
Is there any alternative for that ?
The getOtherKey method has been renamed to getOwnerKey. So you can get the owner key by saying:
$ownerKey = $data->getOwnerKey();

calling a function inside a class from another class php

I am very new to oops in php. Can anyone tell me how can i use a function
public static function getCategories($id_lang = false, $active = true,$order = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
{
if (!Validate::isBool($active))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT *
FROM `' . _DB_PREFIX_ . 'category` c
' . Shop::addSqlAssociation('category', 'c') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . '
WHERE 1 ' . $sql_filter . ' ' . ($id_lang ? 'AND `id_lang` = ' . (int)$id_lang : '') . '
' . ($active ? 'AND `active` = 1' : '') . '
' . (!$id_lang ? 'GROUP BY c.id_category' : '') . '
' . ($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, category_shop.`position` ASC') . '
' . ($sql_limit != '' ? $sql_limit : '')
);
if (!$order)
return $result;
$categories = array();
foreach ($result as $row)
$categories[$row['id_parent']][$row['id_category']]['infos'] = $row;
return $categories;
}
getCategories() is inside a class named class CategoryCore i want to use this getcategory into a new class totalDiscount in which a function called configure_products();
How can i use getcategory() inside the configure products?
include the class file on the page
You can create a object of the class inside another class
function configure_products(){
$categories = new CategoryCore();
$categories->getcategory();
// use $categories to do stuff
......
.....
}
OR
You can call it directly
function configure_products(){
$categories = CategoryCore::getCategories();
.....
....
}
Your function getCategories() is a static function.
So, it can be called without creating object on teh class CategoryCore.
You can use it as (using scope resolution operator):
$categories = CategoryCore::getCategories(YOUR_ARGUMENTS)
Reference

MySQL Syntax Errors code on page

just wondered if someone spot my error i really cant see it but i have sql code on my page starting at get_sql thanks
<?
if (!empty($item_details[$counter]['name'])) {
$main_image = $db -> get_sql_field("SELECT media_url FROM " . DB_PREFIX . "auction_media WHERE
auction_id='" . $item_details[$counter],['auction_id'] . "' AND media_type=1 AND upload_in_progress=0 ORDER BY media_id ASC LIMIT 0,1", 'media_url');
$auction_link = process_link('auction_details', array('name' => $item_details[$counter]['name'], 'auction_id' => $item_details[$counter]['auction_id']));?>
Change
auction_id='" . $item_details[$counter],['auction_id'] . "'
to
auction_id="' . $item_details[$counter]['auction_id'] . '"
here you need " to cover your string not ' & also the comma maybe as echo_Me said
There is a typo in:
$item_details[$counter],['auction_id']
Just remove the comma.
your error is here you have extra comma here
WHERE auction_id='" . $item_details[$counter],['auction_id'] . "'
change to
WHERE auction_id='" . $item_details[$counter]['auction_id'] . "'
TRY this
$main_image = $db->get_sql_field("SELECT media_url FROM " . DB_PREFIX . "auction_media WHERE
auction_id='" . $item_details[$counter]['auction_id'] . "' AND media_type=1 AND upload_in_progress=0 ORDER BY media_id ASC LIMIT 0,1");
Undefined variable: about 12 but i've just realised all my errors are connected my template is not receiving the variables this function is the problem `function set($name, $value) { $this->vars[$name] = $value; }
when i print the request i get this
session Object
(
[vars] => Array
(
[0] =>
)
)
## assign variables that will be used in the template used.
function set($name, $value)
{
$this->vars[$name] = $value;
}
## process the template file
function process($file)
{
#extract($this->vars);
ob_start();
include($this->path . $file);
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}

ModX Revolution Caching Dynamicly Generated Placeholders

How can I cache (using ModX's cacheManager), the dynamic placeholders i am generating here:
// recursive function to generate our un-ordered list of menu items
if(!function_exists('GenerateMenu')){
function GenerateMenu($level, $parent = 0, $wc, $wi, $we, $cs, $sc, $cl){
try {
$lvl = ++$level;
global $modx;
// Check for #1, should this be cached, #2 does it already exist in the cache
$cached = $modx->cacheManager->get('Navigator');
if($sc && isset($cached)){
// need to get the placeholders from cache - here somehow!
return $cached;
}else{
// get the site start
$siteStartId = $modx->getOption('site_start');
// Set our initial rows array
$rows = array();
// Run our query to get our menu items
$sql = 'Select `id`, `menutitle`, `uri`, `longtitle`, `parent`, `link_attributes`, `class_key`, `content`, `alias`, `introtext`
From `' . $modx->getOption(xPDO::OPT_TABLE_PREFIX) . 'site_content`
Where `deleted` = 0 AND `hidemenu` = 0 AND `published` = 1 AND `parent` = :parent
Order by `parent`, `menuindex`';
$query = new xPDOCriteria($modx, $sql, array(':parent' => $parent));
if ($query->stmt && $query->stmt->execute()) {
$rows = $query->stmt->fetchAll(PDO::FETCH_ASSOC);
}
// do some cleanup
unset($query, $sql);
// make sure we have some rows, and then build our html for the menu
if($rows){
// grab a count of our results
$rCt = count($rows);
$cls = ($lvl > 1) ? 'sub-item-' . $lvl : 'main-item-' . $lvl;
$ret .= ' <ul class="' . $cls . '" id="' . $cls . '-' . $parent . '">' . "\r\n";
for($i = 0; $i < $rCt; ++$i){
// if this resource is a WebLink, show the content in it, as the URL for the href tag, otherwise, use the resource's URI
$url = ($rows[$i]['class_key'] == 'modWebLink') ? $rows[$i]['content'] : '/' . $rows[$i]['uri'];
// Check for the site's start id, if true, show a "blank" link, otherwise show the $url
$showUrl = ($siteStartId == $rows[$i]['id']) ? '/' : $url;
$la = (strlen($rows[$i]['link_attributes']) > 0) ? ' ' . $rows[$i]['link_attributes'] : null;
// Set some dynamic placeholders, they can only be used ont he pages that contain this snippet
$modx->toPlaceholders(array('Title-' . $rows[$i]['id'] => $rows[$i]['longtitle'],
'MenuTitle-' . $rows[$i]['id'] => $rows[$i]['menutitle'],
'URL-' . $rows[$i]['id'] => $showUrl),
'link');
$ret .= ' <li class="' . $cls . '" id="' . $rows[$i]['alias'] . '">' . "\r\n";
$ret .= ' <a href="' . $showUrl . '" title="' . $rows[$i]['longtitle'] . '"' . $la . '>' . $rows[$i]['menutitle'] . '</a>' . "\r\n";
$ret .= GenerateMenu($lvl, $rows[$i]['id']);
// Check for a snippet, and render it
$it = $rows[$i]['introtext'];
if($cs && IsSnippet($it)){
// if we find a snippet in the Summary field, run it, and attach it to our output
preg_match('/\[\[!?(.*)\]\]/', $it, $sm);
$ret .= $modx->runSnippet($sm[1]);
// clean up
unset($sm);
}
$ret .= ' </li>' . "\r\n";
}
$ret .= ' </ul>' . "\r\n";
}
// clean up
unset($rows);
// Check to see if we should cache it, if so, set it to cache, and apply the length of time it should be cached for: defaults to 2 hours
if($sc){
// NEED TO SET THE PLACEHOLDERS TO CACHE SOMEHOW
$modx->cacheManager->set('Navigator', $ret, $cl);
}
// return the menu
return $ret;
}
} catch(Exception $e) {
// If there was an error, make sure to write it out to the modX Error Log
$modx->log(modX::LOG_LEVEL_ERROR, '[Navigator] Error: ' . $e->getMessage());
return null;
}
}
}
The easiest solution may be pdoTools which allows you to establish caching at run time.
http://www.shawnwilkerson.com/modx/tags/pdotools/
Also, I do not believe resource placeholders are cached which is the best place to have your items cahced:
case '+':
$tagName= substr($tagName, 1 + $tokenOffset);
$element= new modPlaceholderTag($this->modx);
$element->set('name', $tagName);
$element->setTag($outerTag);
$elementOutput= $element->process($tagPropString);
break;
From lines 455-461 of https://github.com/modxcms/revolution/blob/master/core/model/modx/modparser.class.php#L455
You may notice the other tag types have:
$element->setCacheable($cacheable);
I cover the parser in Appendix D of my book. I found some issues in it in 2011 which Jason corrected.
Move toPlaceholders() to the end of your script and instead cache the array of placeholder data:
// attempt to retrieve placeholders from cache
$placeholders = $modx->cacheManager->get('Navigator');
// if not in cache, run your snippet logic and generate the data
if (empty($placeholders))) {
$placeholders = array(
'myplaceholder' => 'placeholder data'
);
$modx->cacheManager->set('Navigator', $placeholders, $cl);
}
// set placeholders for use by MODX
$modx->toPlaceholders($placeholders);

Categories