Simplify the Doctrine query - mysql

I am new to Doctrine ORM or any ORM
$em = Zend_Registry::getInstance ()->entitymanager;
$p = $em->createQuery ( "
SELECT u
FROM Teon_Model_User u
WHERE u.app_auth IN (:app_auth)" );
$p->setParameter ( 'app_auth', $app_auth );
$array = $p->getArrayResult();
$customer_id = $array[0]['customer_id'];
$p = $em->createQuery ( "
SELECT p
FROM Teon_Model_Purchase p
WHERE p.customer IN (:customer_id)" );
$p->setParameter ( 'customer_id', $customer_id );
$array = $p->getArrayResult();
$purchase_id = $array[0]['id'];
$p = $em->createQuery ( "
SELECT pm
FROM Teon_Model_PurchaseManual pm
WHERE pm.purchase_id IN (:purchase_id)" );
$p->setParameter ( 'purchase_id', $purchase_id );
$array = $p->getArrayResult();
$m_id = $array[0]['manual_id'];
Can you simplify this query, it looks so stupid, I am using Doctrine in zend framework
this query is to authenticate the user whether he has manual_id in his purchases by supplying a authentication code..

Here's the 2 simple way i could think of to do this:
<?php
$em = Zend_Registry::getInstance()->entitymanager;
// 1st way
$user = $em->getRepository('Teon_Model_User')->findOneByAppAuth($app_auth);
$user->getCustomerId();
// 2nd way
$user = $em->getRepository('Teon_Model_User')->findOneBy(array(
'app_auth' => $app_auth,
));
$user->getCustomerId();

Related

Rewrite SQL Select to use $wpdb->prepare

I'm trying to rewrite an SQL select query to use the $wpdb->prepare function. My original SQL query looks like this and works fine.
function hfwp_SaveFormData($formData, $userID, $today, $dbTable) {
global $wpdb;
$wpdb->show_errors();
$query = "SELECT UserID FROM $dbTable WHERE Date = '$today' AND UserID = '$userID'";
$wpdb->get_results( $query );
$count = $wpdb->num_rows;
if ($count > 0) {
$wpdb->update($dbTable, array('Distance' => $formData), array('Date' => $today, 'UserID' => $userID));
}else{
$wpdb->insert($dbTable, array('UserID' => $userID, 'Date' => $today, 'Distance' => $formData));
}
}
I then tried to rewrite the SELECT statement to use $wpdb->prepare:
$wpdb->get_results( $wpdb->prepare("SELECT UserID FROM %s WHERE Date = %s AND UserID = %d", $dbTable, $today, $userID ) );
But it gives an error in the log but not enough to give me a hint on what is wrong.
I also tried another version of the $wpdb->prepare:
$query = "SELECT UserID FROM %s WHERE Date = %s AND UserID = %d";
$prepared = $wpdb->prepare( $query , $dbTable, $today, $userID );
$wpdb->get_results( $prepared );

Convert raw sql to ZF2 statement

In zf2, how can i write following mysql query and execute it. ??
SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title,'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0) result ON um.module_id = result.id
WHERE um.user_id='3'
I found solution!!
$userId = '1';
$select = "SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title, 'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0)) temptable on um.module_id = temptable.id where um.user_id='". $userId ."'";
$resultSet = $this->adapter->query($select);
return $data = $this->resultSetPrototype->initialize($resultSet->execute())->toArray();
OR else can use ZF2 method:
$sql = new Sql($this->getAdapter());
$select = $sql->select()->from(array('um' => $this->table));
Get all slideshow modules
$select1 = $sql->select(array())->from(
array("slideshow" =>'slideshow_master'))
->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
$select1 = $sql->select(array())->from(
array("slideshow" =>'slideshow_master'))
->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
$select1->where("slideshow.is_deleted = 0");
$select1->order("slideshow.id");
Get all video modules
$select2 = $sql->select(array())->from(
array("video" => 'video_master'))
->columns(
array('id','module_code','module_title',"type" => new Expression("'Video'")));
$select2->where("video.is_deleted = 0");
$select2->order("video.id");
union of two first selects
$select1->combine ( $select2, 'UNION' );
$select->join(array('result' => $select1), "result.id = um.module_id");
$select ->where("um.user_id='". $userId. "'");
$statement = $sql->prepareStatementForSqlObject($select);
return $this->resultSetPrototype->initialize($statement->execute())->toArray();
Sorry for my typing and formatting.

How can I implement a multi join in Typo3 via userfunction?

I want to implement the following sql query:
SELECT title
FROM sys_category
JOIN sys_category_record_mm ON sys_category.uid = sys_category_record_mm.uid_local
JOIN tt_content ON sys_category_record_mm.uid_foreign = tt_content.uid
WHERE tt_content.uid = 645
If I execute this query directly via phpmyadmin it is working, but if I try the following via userfunction the content of $row is false, so I think the syntax for my multi join must be wrong. Hope you can help me :)
public function getCategories()
{
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery
(
'title',
'sys_category JOIN sys_category_record_mm ON sys_category.uid = sys_category_record_mm.uid_local JOIN tt_content ON sys_category_record_mm.uid_foreign = tt_content.uid',
'sys_category.uid = 645'
);
$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc( $res );
var_dump( $row );
}
My bad, the problem was, that I used
'sys_category.uid = 645'
instead of
'tt_content.uid = 645'

query with parentheses in zend framework 2.2

I want my query like this:
SELECT tbl_bids. * , tbl_department.vDeptName, tbl_user.vFirst
FROM tbl_bids
LEFT JOIN tbl_bids_department ON tbl_bids_department.iBidID = tbl_bids.iBidID
LEFT JOIN tbl_department ON tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID
LEFT JOIN tbl_user ON tbl_user.iUserID = tbl_bids.iUserID
WHERE tbl_user.iUserID = '1' // with parantheses in where clause
AND (
tbl_department.vDeptName = 'PHP'
OR tbl_department.vDeptName = 'android'
)
GROUP BY tbl_bids.iBidID
ORDER BY iBidID DESC
LIMIT 0 , 30
But i can't find the way to get parantheses in my query,there are mutiple condition and loop will be there to make where clause..
here is my code
$select = $this->tableGateway->getSql()->select();
$select->columns(array('*'))
->join('tbl_bids_department', 'tbl_bids_department.iBidID = tbl_bids.iBidID', array(),"LEFT")
->join('tbl_department', 'tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID',array(tbl_department.vDeptName),"LEFT")
->join('tbl_user', 'tbl_user.iUserID = tbl_bids.iUserID',array(tbl_user),"LEFT")
->group('tbl_bids.iBidID');
$where = new \Zend\Db\Sql\Where();
$where->equalTo( 'tbl_bids.eDeleted', '0' );
$sWhere = new \Zend\Db\Sql\Where();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if (isset($data['sSearch_'.$i]) && $data['sSearch_'.$i] != "")
{
if($aColumns[$i] == 'vDeptName'){
$allDept = explode(',', $data['sSearch_'.$i]);
foreach ($allDept as $key => $value) {
if($key == 0)
$sWhere->AND->equalTo("tbl_department.vDeptName", $value);
else
$sWhere->OR->equalTo("tbl_department.vDeptName", $value);
}
}elseif($aColumns[$i] == 'vFirst')
$sWhere->AND->equalTo("tbl_user.iUserID",$data['sSearch_'.$i]);
else
$sWhere->AND->like("tbl_bids.".$aColumns[$i], "%" . $data['sSearch_'.$i] . "%");
$select->where($sWhere); // here my where clause is create
}
}
//var_dump($select->getSqlString());
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
I have others many fields to pass through where which also have same problem of paratheses
if there is no any condition i can use nest() and unnest() predicate , but it will show me that string is not nested error,
So pls help me to find the solution.
Pls attach example with solution.
here is a short example
$where = new Sql\Where();
$where->equalTo('col',thirdVal')
->NEST //start braket
->equalTo('col','someVal')
->OR
->equalTo('col','secondVal')
->UNNEST //close bracet
hope this will help

Yii CDbCriteria query matching mutiple rows in one table

I'm trying to figure out how to build a query using Yii's CDbCriteria that would be equivalent to the following:
SELECT
*
FROM
user u
JOIN (
SELECT *
FROM skill_assessment s
WHERE s.skill = 'HTML'
AND s.score >= 80
) b ON
(u.id = b.userId)
JOIN (
SELECT *
FROM skill_assessment s
WHERE s.skill = 'CSS3'
AND s.score >= 80
) c ON
(u.id = c.userId);
etc...
Here's what I have so far, that isn't working:
$criteria = new CDbCriteria();
$criteria->alias = "u";
$criteria->select = "*";
$criteria->join = "JOIN skill_assessment s ON (u.id=s.userId)";
for($i = 0; $i < count($skill_filters); $i++) {
$criteria->addCondition("s.skill='".$skill_filters[$i]->skill."' AND s.score >= ".$skill_filters[$i]->level);
}
$users = UserModel::model()->findAll($criteria);
Any help would be greatly appreciated.
Thanks in advance.
EDIT:
I was able to build out the sql query as a string and use findAllBySql, which returned the correct UserModels that matched my search criteria, the problem is that I haven't been able to get it to return the related SkillAssessmentModels. They don't come back either with the initial query, like this:
$users = UserModel::model()->with('skill_assessments')->findAllBySql($sql);
nor if I get the results like this:
$users = UserModel::model->findAllBySql($sql);
foreach($users as $user)
{
$user->skill_assessments = $user->getRelated('skill_assessments');
}
Any thoughts on how I can get those related models?
The strange thing is that elsewhere in my application, I CAN get the related models if I do this:
$user = UserModel::model->findByPk($id);
$user->skill_assessments->getRelated('skill_assessments');
Second param for addCondition is by default 'AND'. Is this what you are looking for? May be you should define 'OR' for $operator and add braces around condition.
But in your case addCondition will by applied to the user table, not to the JOIN.
I think that this should work for you:
$criteria = new CDbCriteria();
$criteria->alias = "u";
$criteria->together= "skill_assessment";
$where = array();
for($i = 0; $i < count($skill_filters); $i++) {
$where[] = "(s.skill='".$skill_filters[$i]->skill."' AND s.score >= ".$skill_filters[$i]->level . ')';
}
$criteria->join = 'JOIN skill_assessment s ON (u.id=s.userId' . ( $where ? ( ' AND (' . join( ' OR ', $where ) . ')' ) : '') . ')';
$users = UserModel::model()->findAll($criteria);
Fetch _skill_assessment_ like this:
foreach( $users->skill_assessment as $skill_assessment )
{
echo $skill_assessment->userId;
}
At this level keep it simple:
$sql="select * from mytable where id = :id";
$cmd = Yii::app()->db->createCommand($sql)->bindParam("id", $res_id);
$cmd->execute();
Thanks a lot to Boris Belenski!
What you suggested wasn't quite what I needed, but it did get me to what I needed. Here is what I ended up with that works:
$str = "abcdefghijklmnopqrstuvwxyz";
$idxs = str_split($str);
$criteria = new CDbCriteria();
$criteria->alias = "u";
$joins = array();
for($i = 0; $i < count($skill_filters); $i++)
{
$joins[] = " JOIN (SELECT * FROM skill_assessment s WHERE s.skill = '" . $skill_filters[$i]->skill ."' AND s.score >= " . $skill_filters[$i]->level . ") " . $idxs[$i] . " ON (u.id = " . $idxs[$i] . ".userId) ";
}
$criteria->join = join(' ', $joins);
$users = UserModel::model()->findAll($criteria);
foreach($users as $user)
{
$user->skill_assessments = $user->getRelated('skill_assessments');
}
The really key part is that $joins array.
This will allow you to get all the users that match ALL the criteria for row matches in the skill_assessments table.
Also, I could probably lazily load the skill assessments in the View in a normal view, but I need to get all the skill_assessments for each user now in order to pass them back in an ajax response with the user.