I am using symfony 1.4 with Doctrine ORM. I am editing some of the actions, and I need to rewrite a Propel query into Doctrine. Here's the snippet:
$c = new Criteria();
$c->add(BlogCommentPeer::BLOG_POST_ID, $request->getParameter('id'));
$c->addAscendingOrderByColumn(BlogCommentPeer::CREATED_AT);
$this->comments = BlogCommentPeer::doSelect($c);
Can anyone help with the conversion? Thanks.
In your BlogCommentTable.php file, put this method :
public functoion retrieveByPostId($post_id)
{
$q = $this->createQuery('c')
->where('c.blog_post_id = ?', array($post_id))
->orderBy('c.created_at ASC');
return $q->execute();
}
And in your action:
$this->comments = Doctrine_Core::getTable('BlogComment')->retrieveByPostId($request->getParameter('id'));
Related
How can I truncate a table with CakePHP 3.x
I get the truncate query by this:
$this->Coupons->schema()->truncateSql($this->Coupons->connection());
but what is the best practice to execute it
This code working well, thanks to #ndm for his comment that helped the answer to be better.
//In Coupons Controller
$this->Coupons->connection()->transactional(function ($conn) {
$sqls = $this->Coupons->schema()->truncateSql($this->Coupons->connection());
foreach ($sqls as $sql) {
$this->Coupons->connection()->execute($sql)->execute();
}
});
In CakePHP4 you can use the following code to truncate a table:
$table = $this->Coupons;
$sqls = $table->getSchema()->truncateSql($table->getConnection());
foreach ($sqls as $sql) {
$table->getConnection()->execute($sql)->execute();
}
I tested following and it's worked:
$connection = $this->Coupons->getConnection();
$connection->query('TRUNCATE coupons');
Reference: https://book.cakephp.org/4/en/orm/database-basics.html#executing-queries
Read more here: https://book.cakephp.org/4/en/orm/database-basics.html#using-transactions
I need to use where clause on yii, below of my code, I need to add where activated == 0 && send_email == 0.
$model = User::model()->findAll();
Thanks
There are multiple ways to do this:
$model = User::model()->findAll('activated=0 AND send_email=0');
Or,
$model = User::model()->findAll('activated=:activated And send_email=:sendEmail',
array(':activated'=>0,':sendEmail'=> 0));
Or,
$criteria = new CDbCriteria;
$criteria->condition='activated=:activated AND send_email=:sendEmail';
$criteria->params=array(':activated'=>0,':sendEmail'=>0);
$model=User::model()->findAll($criteria);
Or,
$model = User::model()->findAllByAttributes(array('activated'=>0, 'send_email'=>0));
Or,
$model = User::model()->findAllBySql('SELECT * FROM user WHERE activated=:activated AND send_email=:sendEmail', array(':activated'=>0, 'sendEmail'=>0));
More info here. Hope that helps :)
Simply try this:
$model = User::model()->findAll(array("condition"=> "activated=0 AND send_email=0"));
I wanto to sipmly iaterate the result in view. Problem is that it do not accually work. What is missing? I read the documentatnion but they do not give a full ansver how to retrieve data by cusotm query. For me as a beinnger is hard to understend what do next ? I mean about this query I know how to pass it to view by viewmodel et. Please Help.
$config = $this->getServiceLocator()->get('config');
$adapter = new \Zend\Db\Adapter\Adapter($config[db]);
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('brokerzy');
$select->where(array('broker_status' => 'publish'));
$stm = $sql->prepareStatementForSqlObject($select);
$results = $stm->execute();
First, you probably shouldn't be doing queries in your controller, that's bad practice. These queries should be moved behind a service interface.
However, to answer your question (if I understand it), to pass the results of your query to a view, you should use a view model. It would look something like this.
//Your Code
$results = $stm->execute();
$viewModel = new \Zend\View\Model\ViewModel();
$viewModel->results = $results;
return $viewModel;
Is it possible for to sql inject a ZEND_DB_TABLE_ABSTRACT method?
like for example
$this->insert();
edit for a more clearer explanation
Post values are :
'username' = 'admin';
'password' = '1;Drop table users;'
Here is the insert statement in the controller:
public function InsertAction() {
$postValues = $this->_request->getPost();
$usersTable = new Application_Models_DbTable_Users();
$username = $postValues['username'];
$password = $postValues['password'];
$data = array('username'=>$username,'password'=>$password);
$users->insert($data);
}
Yes, it is possible, but in the usual uses of insert() it's not probable. Unless you are using Zend_Db_Expr, you should be safe, because insert() uses prepared statements.
See this post from Bill Karwin for other methods and details.
Check the manual of Zend Zend_Db_Table
It will show you who you can create your own method.
Does anyone know how to convert NHibernate HQL to SQL Scripts?
Since HQL translation depends on your mappings and also runtime behaviour, I think it is unlikely there is a way to do so statically.
You could run the HQL against a real database and capture the generated SQL either via a profiler for your specific rdbms or NHProf.
My old trainings. That was beta-version. Here it is! (hql2sql.jsp)
<SCRIPT type="text/javascript">
<%
org.hibernate.Session ThisSession = SessionFactory.getSession();
org.hibernate.engine.SessionImplementor ThisSessionImplementor = (org.hibernate.engine.SessionImplementor) ThisSession;
org.hibernate.engine.SessionFactoryImplementor ThisSessionFactory = (org.hibernate.engine.SessionFactoryImplementor) ThisSession.getSessionFactory();
String HQL_Query = "SELECT ... ";
String SQL_Query;
try{
org.hibernate.engine.query.HQLQueryPlan HQL_Query_Plan = new org.hibernate.engine.query.HQLQueryPlan(HQL_Query, true, ThisSessionImplementor.getEnabledFilters(), ThisSessionFactory);
SQL_Query = org.apache.commons.lang.StringUtils.join(HQL_Query_Plan.getSqlStrings(), ";");
}catch(Exception e){SQL_Query = "ERROR!! :: " + e.getMessage();}
%>
$(document).ready(function(){
$('span[role="HQL"]').text(" <%=HQL_Query%>");
$('span[role="SQL"]').text(" <%=SQL_Query%>");
});
</SCRIPT>
<div style="border:2px solid brown">
Ваш запрос на HQL:
<br/><br/><span role="HQL"> </span>
</div>
<br>
<div style="border:2px solid green">
Ваш запрос на SQL:
<br/><br/><span role="SQL"> </span>
</div>
I'm not familiar with all the parameters, but this seems to work:
ISessionFactory sessionFactory = ...
var sf = (SessionFactoryImpl) sessionFactory;
var hql = "from Person";
var qt = sf.Settings.QueryTranslatorFactory.CreateQueryTranslator("", hql, new Dictionary<string, IFilter>(), (ISessionFactoryImplementor) sessionFactory);
qt.Compile(new Dictionary<string, string>(), true);
var sql = qt.SQLString;
Console.WriteLine(sql);
I'm not sure what the value of auto-converting HQL to SQL is dynamically...
What exactly are you trying to accomplish by this?
The easiest way would be to run your code while running SQL Server Profiler to see the generated SQL. But a better approach would be to download nhProf (www.nhprof.com) and use that with your code. You will be able to see exactly what your code is outputting in SQL and it will format and color code it and also give you tips on ways to improve your usage of nhibernate.
With NHibernate 3.2, this seems to be the easiest way to get the SQL from an HQL query:
private string GetSQL(string hql)
{
using (var iSession = ...)
{
var session = (NHibernate.Engine.ISessionImplementor)iSession;
var sf = (NHibernate.Engine.ISessionFactoryImplementor)iSession.SessionFactory;
var sql = new NHibernate.Engine.Query.HQLStringQueryPlan(hql, true, session.EnabledFilters, sf);
return string.Join(";", sql.SqlStrings);
}
}
Here is how to do it with NH 5.2 (see https://stackoverflow.com/a/55542462/2047306)
public static string HqlToSql(string hql, ISession session)
{
var sessionImp = (ISessionImplementor)session;
var translatorFactory = new ASTQueryTranslatorFactory();
var translators = translatorFactory.CreateQueryTranslators(new NHibernate.Hql.StringQueryExpression(hql),
null, false, sessionImp.EnabledFilters, sessionImp.Factory);
var hqlSqlGenerator = new HqlSqlGenerator(((QueryTranslatorImpl)translators[0]).SqlAST, sessionImp.Factory);
hqlSqlGenerator.Generate();
return hqlSqlGenerator.Sql.ToString();
}