TYPO3 Repository add new query - repository

I have a little problem.
How do I add the following to my repository?
repository by pastebin.com
I would also like to add the following.
$date = new \DateTime('midnight');
$query->matching(
$query->greaterThanOrEqual('date', $date->format('Y-m-d H:i:s'))
);
Separate from each other it works.
Thanks

It works!
...
$query->matching(
$query->logicalAnd(
$query -> logicalAnd($constraints),
$query->greaterThanOrEqual('date', $date->format('Y-m-d H:i:s'))
)
);
...

Related

SQL query to Laravel

I am trying to convert the following query to Laravel:
select libéllé
from application
where libéllé not in (select application_id from application_user
where user_id = $id)
Laravel whereNotIn supports closures for subqueries, so it will be as simple as this:
Using Eloquent:
// Add this to top of your file.
use App\{ Application, ApplicationUser };
// Get your entries.
$rows = Application::whereNotIn('libéllè', function($query) use ($id) {
$query->select('application_id')->from((new ApplicationUser)->getTable())->where('user_id', $id);
})->get(['libéllè']);
Using Query Builder:
$rows = DB::table('application')->whereNotIn('libéllè', function($query) use ($id) {
$query->select('application_id')->from('application_user')->where('user_id', $id);
})->get(['libéllè']);
Please Try it.
$results = DB::select(
select libéllé
from application
where (libéllé)
not in(
select application_id from application_user
where user_id = $id
)
);
Also see this answer: How to convert mysql to laravel query builder
Also see this documentation: https://laracasts.com/discuss/channels/laravel/laravel5-resolve-username-from-2-tables?page=1

YII Console Application (CConsoleCommand)

Good time! There is a project on Yii, you need to organize operations for CRONu through console applications. Once a month, the script adds a record to the table.
class ZpEduCommand extends CConsoleCommand {
public function run($args) {
$command = Yii::app()->db->createCommand('INSERT INTO `text`(`ID`, `datee`, `ggg`) VALUES ("123123","2014-12-01 00:00:00","123")');
$command->execute();
}
All works well. If so put the date, nothing is added.
$command = Yii::app()->db->createCommand('INSERT INTO `text`(`ID`, `datee`, `ggg`) VALUES ("123123","' . date('Y-m-d H:i:s') . '","123")');
$command->execute();
Make sure that ID is not primary key in table because primary key should be unique but in your example they are the same.
Also better use query builder for operations with database:
$command = Yii::app()->db->createCommand();
$command->insert('text', array(
'datee'=>date('Y-m-d H:i:s'),
'ggg'=>'123',
));

Laravel Order By a alias

in code below i get a user_name columm not found if i remove my "workaround", how i can set the alias before the get command? have a trick?
//Select
$qb = DB::table('log as l');
//Joins
$qb->join('user as u', 'l.user_id', '=', 'u.id');
//Orders
if($sort[0]["field"]=="user_name")// This is a workaround for my problem
$sort[0]["field"] = "u.name";
$qb->orderBy($sort[0]["field"],$sort[0]["dir"]);
//Wheres
Data::applyFilter($qb,$filters);
$total = $qb->count("l.id");
$qb->skip($skip)
->take($take);
$result = $qb->get(array("l.id", "l.action", "l.entity_type", "l.entity_id", "u.name as user_name", "l.datetime"));
In documentation there is
$users = DB::table('users')->select('name as user_name')->get();
If you set a key-value variable instead of "user_name" it should do what you want ?
Bye

Extbase - get created sql from query

i want to get some database tables from my typo3 extensions.
The Extension is based on extbase.
The query always returns nothing but the data exists
I've tried this:
$query = $this->createQuery();
$query->statement('SELECT * FROM `my_table`
WHERE field = ? ORDER BY date DESC LIMIT 1',
array($condition));
$results = $query->execute();
and this:
$query = $this->createQuery();
$query->matching($query->equals('field', $condition));
$query->setOrderings(array('date' => Tx_Extbase_Persistence_QueryInterface::ORDER_DESCENDING));
$query->setLimit(1);
$results = $query->execute();
both returns null as result.
Is it possible to get the sql that the class creates to look where the bug is?
I've looked in some extbase persistent classes but didn't find a clue
EDIT:
For those who are interested.. i found a "solution".
If you create the query with the statement() method, you can print the query with this function
echo $query->getStatement()->getStatement();
It doesn't replace the placeholder.
But you can get the Variables with this method
var_dump($query->getStatement()->getBoundVariables());
Thats the best Solution that i found, without editing the extbase extenstions
In TYPO3 6.2 you can use Extbase DebuggerUtility to debug the query.
Add this code before $query->execute():
$queryParser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Storage\\Typo3DbQueryParser');
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($queryParser->parseQuery($query));
For TYPO3 8.7+ use this code instead:
$queryParser = \TYPO3\CMS\Core\Utility\GeneralUtilityGeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Persistence\Generic\Storage\Typo3DbQueryParser::class);
$doctrineQueryBuilder = $queryParser->convertQueryToDoctrineQueryBuilder($query);
$doctrineQueryBuilderSQL = $doctrineQueryBuilder->getSQL();
$doctrineQueryBuilderParameters = $doctrineQueryBuilder->getParameters();
Check this snippet, although it's not very comfortable in use it helps a lot:
in general you need this code at the end of the buildQuery(array $sql) method (*) - right before return $statement;
if (in_array("your_table_name", $sql['tables'])) {
var_dump($statement);
print_r($statement);
}
(*) Class file:
TYPO3 ver.: 4.x: typo3/sysext/extbase/Classes/Persistence/Storage/Typo3DbBackend.php
TYPO3 ver.: 6.x: typo3/sysext/extbase/Classes/Persistence/Generic/Storage/Typo3DbBackend.php
In 6.2.x ...
You can try within \TYPO3\CMS\Core\Database\DatabaseConnection::exec_SELECTquery method, just add the condition after fetching the $query, like (trim is important!):
public function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
$query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
if (trim($from_table) == 'fe_users') {
DebuggerUtility::var_dump($query);
}
// rest of method
An easy way without changing any Typo3 core code and not mentioned in any forum so far is using the php "serialize()" method:
$result = $query->execute();
echo (serialize($result));
In the result object you find the SQL query ("statement;" ...)
Improvement to biesiors answer:
As Extbase replaces some placeholders after calling buildQuery(), you might prefer to place the debug output into getObjectDataByQuery(), just after $this->replacePlaceholders($sql, $parameters, $tableName);
if (strpos($sql, "your_table_name.")) {
debug($sql, 'my debug output');
};
Also, better use debug() instead of var_dump().
[File: typo3\sysext\extbase\Classes\Persistence\Generic\Storage\Typo3DbBackend.php. Line 339 in version 6.1]:
$query = $this->createQuery();
$query->getQuerySettings()->setReturnRawQueryResult(TRUE);
$getHotelInfo = 'SELECT * FROM `my_table` WHERE field = ? ORDER BY date DESC LIMIT 1';
return $query->statement($getHotelInfo)->execute();
For executing query you have to write 'setReturnQueryResult' on your repository
I just extended the above snippet, with a $_GET condition.
for debugging, just append "?dbg_table=tx_some_of_my_tables" to your address, and you're ready to go ;-)
if (in_array($_GET['dbg_table'], $sql['tables'])) {
echo('<div style="background: #ebebeb; border: 1px solid #999; margin-bottom: 20px; padding: 10px;"><pre style="white-space: normal">'.$statement.'</pre></div>');
}
A cleaner way to debug your statements when using TYPO3 6.1 is to use the query parser of Typo3DbBackend.
$parser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Storage\\Typo3DbBackend');
$params = array();
$queryParts = $parser->parseQuery($query, $params);
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('query', 'my_extension', 1, array('query' => $queryParts, 'params' => $params));
The parser returns an array containing the different parts of the generated SQL statement.
With TYPO3 6.2 the parseQuery method was moved to Typo3DbQueryParser and lost its second parameter.
i suggest set this in typo3conf/LocalConfiguration.php file under 'SYS' array
'SYS' => array(
......
'displayErrors' => 1,
'sqlDebug' => 1
.......
)
and then write wrong field name in query intentionally and then execute code.
this will show last query execute with error.

how do I delete rows in Yii?

Using Yii, I want to delete all the rows that are not from today.
Is my solution ok ?
$query = "delete from `user_login_hash` where `day`!='".(date('Y-m-d',time()))."'";
Yii::app()->db->createCommand($query);
A prettier solution is
YourUserModel::model()->deleteAll("day !='" . date('Y-m-d') . "'");
Better user PDO parameters and on command you also have to call execute
$query = "delete from `user_login_hash` where `day`<> :date";
$command = Yii::app()->db->createCommand($query);
$command->execute(array('date' => date('Y-m-d')));
or
UserLoginHash::model()->deleteAll(
'day <> :date',
array('date' => date('Y-m-d'))
);
Try this...
$query = "delete from `user_login_hash` where `day`!='".(date('Y-m-d',time()))."'";
$query->queryAll($query);
You may use query builder
$command = Yii::app()->db->createCommand()
->delete('user_login_hash', 'day !=' . date('Y-m-d'));
http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder#sec-15