Applying multiple conditions in zf2 left join - php

I have a zf2 left join query like this
$select->join(
'contractor_jobs',
'contractor_jobs.contractor_id = contractor_info.contractor_id',
array('job_trade_id'),
$select::JOIN_LEFT
);
I want to apply another condition as 'contractor_jobs.job_trade_id = $variableName' during joining. please help me.

You can use expression:
$join = new \Zend\Db\Sql\Expression('contractor_jobs.contractor_id = contractor_info.contractor_id AND
contractor_jobs.job_trade_id = '.$variableName.' ');
$select->join(
'contractor_jobs',
$join,
array('job_trade_id'),
$select::JOIN_LEFT
);

Related

cake php custom query

I have use custom query in cakephp but I dont understand how to run custom join query.
I am using this code
$arrayTemp1 = $this->User->query('SELECT DISTINCT
u.id,u.hunting_association FROM ht_users as u LEFT JOIN
`ht_user_animal_prices` as uap ON uap.user_id=u.id WHERE
uap.animal_type_id='.$this->request->data['User']['animal'].' ');
User is the model for ht_users and UserAnimalPrice is the model for ht_user_animal_prices. How to combine the query?
Please help.
If you want to use custom queries and you want the data of UserAnimalPrice model, you just have to put the fields in the query. Something like:
$arrayTemp1 = $this->User->query('SELECT DISTINCT u.id,u.hunting_association, uap.* FROM ht_users as u LEFT JOIN ht_user_animal_prices as uap ON uap.user_id=u.id WHERE uap.animal_type_id='.$this->request->data['User']['animal'].' ');
If you prefer not to use custom queries:
$fields = array('User.id','User.hunting_association','UserAnimalPrice.*');
$join = array(
array(
'table' => 'ht_user_animal_prices',
'alias' => 'UserAnimalPrice',
'type' => 'LEFT',
'conditions' => array('UserAnimalPrice.user_id = User.id')
)
);
$conditions = array('UserAnimalPrice.animal_type_id' => $this->request->data['User']['animal']);
$group = array('User.id');
arrayTemp1=arrayTemp1->find('all',array('fields'=>$fields,'joins'=>$join,'conditions'=>$conditions,'group'=>$group));
This is Correct Query u used .You can also use it in User Model like
public function getCustomUsersQuery()
{
$arrayTemp1 = $this->query("
SELECT
DISTINCT u.id,u.hunting_association FROM ht_users as u
LEFT JOIN
ht_user_animal_prices as uap ON uap.user_id=u.id
WHERE
uap.animal_type_id='".$this->request->data['User']['animal']."'");
return $arrayTemp1;
}
And call inside Users Controller
$result = $this->getCustomUsersQuery();
Sorry I cannot comment on Rizwan answer. If you received the "Call to a member function..." problem, make sure you have the following code
public $uses = array('User');
this tells that you want to access the user model in that controller. Then you will be allowed to do so.

Symfony createNativeQuery, add count()

I have a query in a repository like :
$rsm = new ResultSetMapping;
$rsm->addEntityResult('\My\ProjectBundle\Entity\News', 't');
$rsm->addFieldResult('t', 'id', 'id');
$rsm->addMetaResult('t', 'account_id', 'account_id');
$qb = $this->_em->createNativeQuery(
'SELECT t.*
FROM news as t
LEFT JOIN
LEFT JOIN
WHERE
CONDITIONS CONDITIONS
',
$rsm
);
return $qb->getResult();
I simplified the above query which is used to retrieve the news that meet specific conditions.
I need to add a count() function to this query.
I have an other ManyToOne entity-relationship between Comment and News.
How to modify the query to get the comments number a given news has ?
I'm trying to add a left join to comment and add Count() in the select but I always get errors. How could I resolve this problem ?
Raw SQL with Doctrine is easier like this :
$em = $this->getDoctrine()->getManager()->getConnection();
$query = "
SELECT t.*
FROM news as t
LEFT JOIN
LEFT JOIN
WHERE
CONDITIONS CONDITIONS
";
$stmt = $em->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();

Delete rows with Laravel query builder and LEFT JOIN

How to delete rows from multiple tables in one query (with left join).
The query:
DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` ....
So, I try it like this:
DB::table('deadline', 'job')
->leftJoin('job', 'deadline.id', '=', 'job.deadline_id')
->where('deadline.id', $id)
->delete();
Seems that Laravel doesn't support delete from multiple tables with left join.
Is there a supported way or workaround?
It seems that my way is not possible. So, I did it like this.
$q = 'DELETE deadline, job FROM deadline LEFT JOIN job ...where deadline.id = ?';
$status = \DB::delete($q, array($id));
Documentation: http://laravel.com/docs/database#running-queries
DB::table(DB::raw('deadline, job')) might work. If it doesn't, you'll have to write the SQL manually and call it via DB::statement().
To make laravel allow a join in a delete is simple - you just need to change the compileDelete function in Illuminate\Database\Query\Grammars\Grammar to this:
public function compileDelete(Builder $query)
{
$table = $this->wrapTable($query->from);
$components = implode(' ', array(
is_array($query->joins) ? $this->compileJoins($query, $query->joins) : '',
is_array($query->wheres) ? $this->compileWheres($query, $query->wheres) : '',
is_array($query->limit) ? $this->compilelimit($query, $query->limit) : '',
is_array($query->offset) ? $this->compileOffset($query, $query->offset) : ''
));
return trim("delete $table from $table ".$components);
}
Then ->delete() will work the way you expect it to. I've already added this as a pull request to the laravel framework repo, so hopefully this might be merged into the next version - just have to see.
$query = 'DELETE courses,course_contents FROM courses
INNER JOIN course_contents ON course_contents.course_id = courses.id
WHERE courses.id = ?';
\DB::delete($query, array($id));

How to use CDbCriteria in Yii to apply SQL filters on Model

I try to get this mysql query to work with Yii model but i can't.
SELECT COUNT( qhc.countries_id) AS counter, q.question, co.name
FROM questions AS q , countries as co, questions_has_countries AS qhc
WHERE qhc.questions_id = q.id
AND co.id = qhc.countries_id
GROUP BY question
HAVING counter = 2
So far i have this, but somehow thou it seems ok, it doesnt work :
$criteria = new CDbCriteria();
$criteria->select = 'question, COUNT(countries_id) as counter';
$criteria->with = array('countries', 'categories');
$criteria->addInCondition('countries.id' , $_POST['Questions']['countries']);
$criteria->group = 'question';
$criteria->having = ('counter = 1');
$model = Questions::model()->findAll($criteria)
Pls help, I'am pretty new to Yii framework.
Thanks.
Sql from the log :
SELECT `t`.`question` AS `t0_c1`,
COUNT(countries_id) as counter, `t`.`id` AS `t0_c0`, `countries`.`id` AS
`t1_c0`, `countries`.`name` AS `t1_c1`, `categories`.`id` AS `t2_c0`,
`categories`.`name` AS `t2_c1` FROM `questions` `t` LEFT OUTER JOIN
`questions_has_countries` `countries_countries` ON
(`t`.`id`=`countries_countries`.`questions_id`) LEFT OUTER JOIN `countries`
`countries` ON (`countries`.`id`=`countries_countries`.`countries_id`)
LEFT OUTER JOIN `questions_has_categories` `categories_categories` ON
(`t`.`id`=`categories_categories`.`questions_id`) LEFT OUTER JOIN
`categories` `categories` ON
(`categories`.`id`=`categories_categories`.`categories_id`) WHERE
(countries.id=:ycp0) GROUP BY question HAVING (counter = 2). Bound with
:ycp0='1'
You have done most of work. Now you need to call the $criteria into model. Just like this
$rows = MODEL ::model()->findAll($criteria);
Where MODEL is model class of table which you want to apply criteria on.
To learn more about this you can follow this CActiveRecord Class.
Try to set together in CDbCriteria
...
$criteria->together = true;
$model = Question::model()->findAll($criteria);
when you use "as counter", your model must have a property named "counter" or it will not load it into your model.
if you don't have a property named "counter", try using another one of your models property that you are not selecting right now : "as someColumn"
and use condition or addCondition or .. instead of having
cheers

codeigniter Database class JOIN USING

how can i use
left JOIN Table2 using(table.id) ?
Example of my CODE
$this->db->select('visits.*,patients.name,workers.dr_name,time(visits.time)');
$this->db->from('visits');
//The next join = LEFT JOIN workers ON visits.worker_id=workers.worker_id
$this->db->join('workers','visits.worker_id=workers.worker_id','left');//WORKING
//The next join = JOIN `patients` ON patient_id --> i want it JOIN patients USING(patient_id)
$this->db->join('patients','patient_id','USING');//NOT WORKING
i searched every were, yet couldnt find a solution, and so i opened and tried to edit JOIN function in db_active_rec.php
/system/database/DB_active_rec.php
and found the join function
public function join($table, $cond, $type = '')
{
if ($type != '')
{
$type = strtoupper(trim($type));
if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER')))
{
$type = '';
}
else
{
$type .= ' ';
}
}
// Extract any aliases that might exist. We use this information
// in the _protect_identifiers to know whether to add a table prefix
$this->_track_aliases($table);
// Strip apart the condition and protect the identifiers
if (preg_match('/([\w\.]+)([\W\s]+)(.+)/', $cond, $match))
{
$match[1] = $this->_protect_identifiers($match[1]);
$match[3] = $this->_protect_identifiers($match[3]);
$cond = $match[1].$match[2].$match[3];
}
// Assemble the JOIN statement
$join = $type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond;
$this->ar_join[] = $join;
if ($this->ar_caching === TRUE)
{
$this->ar_cache_join[] = $join;
$this->ar_cache_exists[] = 'join';
}
return $this;
}
tried to edit the part under "// Assemble the JOIN statement" and put ifcondition to detect USING and then adjust the query accordingly but failed.. epic fail
can any one help ? how can i edit this function so that it would use USING in Join query ?
From the manual:
$this->db->join();
Permits you to write the JOIN portion of your query:
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id
Multiple function calls can be made if you need several joins in one query.
If you need a specific type of JOIN you can specify it via the third parameter of the function. Options are: left, right, outer, inner, left outer, and right outer.
$this->db->join('comments', 'comments.id = blogs.id', 'left');
// Produces: LEFT JOIN comments ON comments.id = blogs.id

Categories