I need to run following statements by CDbCriteria in Yii :
SELECT `tbl_products`.`id` FROM `tbl_products`
INNER JOIN `tbl_producttags`
ON `tbl_products`.`id` = `tbl_producttags`.`product_id`
INNER JOIN `tbl_tags`
ON `tbl_producttags`.`tag_id` = `tbl_tags`.`id`
What I've tried so far :
$criteria = new CDbCriteria();
$criteria->select= '`tbl_products`.`id`';
$criteria->join ='INNER JOIN `tbl_producttags` ON `tbl_products`.`id` = `tbl_producttags`.`product_id`'
. ' INNER JOIN `tbl_tags` ON `tbl_producttags`.`tag_id` = `tbl_tags`.`id`';
$products = Products::model()->findAll($criteria);
But it get me following error :
SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'tbl_products.id' in 'field list'. The SQL statement executed was:
SELECT tbl_products.id FROM tbl_products t INNER JOIN
tbl_producttags ON tbl_products.id =
tbl_producttags.product_id INNER JOIN tbl_tags ON
tbl_producttags.tag_id = tbl_tags.id
The problem is :
It's because of that CDbCriteria added unwanted alias name t after tbl_products
How can I fix it?
Use this
$criteria = new CDbCriteria();
$criteria->select= '`yourAlias`.`id`';
$criteria->alias="yourAlias";
$criteria->join ='INNER JOIN `tbl_producttags` ON `tbl_products`.`id` = `tbl_producttags`.`product_id`'
. ' INNER JOIN `tbl_tags` ON `tbl_producttags`.`tag_id` = `tbl_tags`.`id`';
$products = Products::model()->findAll($criteria);
the alias name of the table. If not set, it means the alias is 't'
Related
I have join many tables in this query via LEFT JOIN and i want to apply condition on table but php is giving me following error
Error Number: 1054 Unknown column '2021-08-23' in 'on clause'
SELECT i.isn_Add_Date, s.scentre_Name, i.isn_Job_No,cp.cpart_Part_Id,
cp.cpart_Part,cp.cpart_Qty,cp.cpart_Rate,cp.cpart_Amount,
p.product_Name,m.model_Name,c.complaint_Job_No,c.complaint_Add_Date,
c.complaint_Under_Warranty,cp.cpart_Qty,cp.cpart_Rate,cp.cpart_Amount
FROM complaints as c LEFT JOIN complaint_parts as cp ON c.complaint_Id
= cp.cpart_Complaint_Id LEFT JOIN scentres as s ON s.scentre_Id = c.complaint_Scentre_Id LEFT JOIN products as p ON p.product_Id =
c.complaint_Product_Id LEFT JOIN models as m ON m.model_Id =
c.complaint_Model_Id LEFT JOIN isn as i ON i.isn_Complain_Number =
c.complaint_Job_No AND i.isn_Add_Date BETWEEN '2021-08-23' AND
'2021-08-26' WHERE c.complaint_Scentre_Id = '1' AND c.complaint_Status
= 'Delivered' AND c.complaint_Trash = 0
here is my php code
$this->db->select('i.isn_Add_Date,s.scentre_Name,i.isn_Job_No,cp.cpart_Part_Id,cp.cpart_Part,cp.cpart_Qty,cp.cpart_Rate,cp.cpart_Amount,p.product_Name,m.model_Name,c.complaint_Job_No,c.complaint_Add_Date,c.complaint_Under_Warranty,cp.cpart_Qty,cp.cpart_Rate,cp.cpart_Amount');
$this->db->join('complaint_parts as cp', 'c.complaint_Id = cp.cpart_Complaint_Id ', 'left');
$this->db->join('scentres as s', 's.scentre_Id = c.complaint_Scentre_Id', 'left');
$this->db->join('products as p', 'p.product_Id = c.complaint_Product_Id', 'left');
$this->db->join('models as m', 'm.model_Id = c.complaint_Model_Id', 'left');
$this->db->JOIN('isn as i', 'i.isn_Complain_Number = c.complaint_Job_No AND i.isn_Add_Date BETWEEN '.str_replace('/', '-', $fromDate).' AND '.str_replace('/', '-', $toDate).'', 'LEFT');
$this->db->where("c.complaint_Scentre_Id", $serviceCenterId[0]);
$this->db->where("c.complaint_Status",'Delivered');
$this->db->where("c.complaint_Trash", 0);
$query = $this->db->get("complaints as c");
change
`2021-08-23` AND `2021-08-26`
to
'2021-08-23' AND '2021-08-26'
as the ` character implies columns and not strings
the sql is ok
maybe the orm can not handle complex join condition
you can move the join condition 【AND i.isn_Add_Date BETWEEN '2021-08-23' AND '2021-08-26'】 to where condition
just like $this->db->where("i.isn_Add_Date", BETWEEN ,['2021-08-23','2021-08-26]);
I've been trying to do a regular query with an inner join in Doctrine's DQL but with little success:
SQL:
SELECT
r.rtsRate
FROM tmc_rates_tbl_rts as r
INNER JOIN tmc_business_rel_buz as b ON (b.buzPcsID = r.rtsBuzID AND b.buzCmrID = r.rtsCmrID)
WHERE b.buzID = :business
AND r.rtsProID = :user;
DQL:
$qb = $this->rateRepo->createQueryBuilder('r')
->select('r.rate')
->innerJoin('r.business', 'business')
->where('r.business = :bid')
->andWhere('r.user = :user')
->setParameter('bid', $time->getBusiness())
->setParameter('user', $this->user)
->getQuery()
->execute();
Doctrine cames out with a double join out of the blue:
An exception occurred while executing 'SELECT t0_.rtsRate AS rtsRate_0 FROM tmc_rates_tbl_rts t0_ INNER JOIN rate_business r2_ ON t0_.id = r2_.rate_id INNER JOIN tmc_business_rel_buz t1_ ON t1_.id = r2_.business_id AND (t1_.buzStatus = 1) WHERE t1_.buzID = ? AND t0_.rtsProID = ?' with params [9, 5]:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'tm_salesn.rate_business' doesn't exist
500 Internal Server Error - TableNotFoundException
I very much appreciate any help
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
I have defined the following criteria in Yii, and tries to use it to fetch an array of customers.
$criteria = new CDbCriteria(array(
"condition"=>"hidden = 0".(Yii::app()->user->GetState('is_admin') ? "" : " AND franchisesMunicipalities.franchise_id=".Yii::app()->user->getState('fid')),
"with" => array('municipality','municipality.franchisesMunicipalities')
));
$customers = Customers::model()->findAll($criteria);
This (i thought) should result in that Yii joined the table Customers with the table Municipalities, and then in the same query join the table Municipalities with the table Franchises_Municipalities. However it doesn't work since it doesn't join franchisesMunicipalities.
The resulting query is this
SELECT `t`.`id` AS `t0_c0`,
`t`.`municipality_id` AS `t0_c1`,
`t`.`personal_code_number` AS `t0_c2`,
`t`.`name` AS `t0_c3`,
`t`.`adress` AS `t0_c4`,
`t`.`zip` AS `t0_c5`,
`t`.`phone` AS `t0_c6`,
`t`.`mobile` AS `t0_c7`,
`t`.`email` AS `t0_c8`,
`t`.`hidden` AS `t0_c9`,
`municipality`.`id` AS `t1_c0`,
`municipality`.`county_id` AS `t1_c1`,
`municipality`.`name` AS `t1_c2`
FROM `customers` `t`
LEFT OUTER JOIN `municipalities` `municipality`
ON ( `t`.`municipality_id` = `municipality`.`id` )
WHERE ( hidden = 0
AND municipality.franchisesmunicipalities.franchise_id = 7 )
LIMIT 30
As you can see it only joins on one relation. The relations in the model should be correctly defined, since i am able to use them in other contexts.
Why doesn't this work?
According to http://www.yiiframework.com/doc/api/1.1/CActiveRecord#with-detail I believe you should be doing it this way:
$criteria = new CDbCriteria(array(
"condition"=>"hidden = 0".(Yii::app()->user->GetState('is_admin') ? "" : " AND franchisesMunicipalities.franchise_id=".Yii::app()->user->getState('fid'))
));
$customers = Customers::model()->with('municipality','municipality.franchisesMunicipalities')->findAll($criteria);
Hopefully that works for you.
I am trying to write a query in yii. I have the following which works
$criteria = new CDbCriteria;
$criteria->condition = "($column = :id)";
$criteria->params = array(":id" => $id );
$rows = Jobs::model()->with('pROJ')->findAll($criteria);
This returns the model of Jobs in array. I need to write the following query in yii to return a model
SELECT jobs.JOBNO, jobs.STATUS, projects.ORDERNO, jobs.PROJID, jobs.NAME, jobs.SEQ, jobs.PCENTDONE, jobs.EARNED, jobs.VALUE, jobs.DATEIN, jobs.DATEDONE, jobs.DATEDUE, jobs.SENTBACK, jobs.ORIGTAPES, jobs.COMMENTS, projects.CATEGORY, orders.BIDNO
FROM (jobs INNER JOIN projects ON jobs.PROJID = projects.PROJID) INNER JOIN orders ON projects.ORDERNO = orders.ORDERNO
where jobs.projid = 3002001
ORDER BY jobs.JOBNO, jobs.PROJID
I have tried the following but it does not work
$rows = Yii::app()->db->createCommand()
->select('jobs.*, projects.ORDERNO, projects.CATEGORY, orders.BIDNO')
->from('jobs, projects, orders')
->join('projects p','jobs.PROJID = p.PROJID')
->join('orders o', 'p.ORDERNO = o.ORDERNO')
->where('jobs.projid=:id', array(':id'=>$id))
->queryRow();
I get the following error
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'jobs.PROJID' in 'on clause'. The SQL statement executed was: SELECT `jobs`.*, `projects`.`ORDERNO`, `projects`.`CATEGORY`, `orders`.`BIDNO`
FROM `jobs`, `projects`, `orders`
JOIN `projects` `p` ON jobs.PROJID=p.PROJID
JOIN `orders` `o` ON p.ORDERNO=o.ORDERNO
WHERE jobs.projid=:id
I have updated to
$rows = Yii::app()->db->createCommand()
->select('jobs.*, projects.orderno, projects.category, orders.bidno')
->from('jobs')
->join('projects p','jobs.projid = p.projid')
->join('orders o', 'p.orderno = o.orderno')
->where('jobs.projid=:id', array(':id'=>$id))
->queryRow();
but i still get the error. All columns in mysql are CAPS
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'projects.orderno' in 'field list'. The SQL statement executed was: SELECT `jobs`.*, `projects`.`orderno`, `projects`.`category`, `orders`.`bidno`
FROM `jobs`
JOIN `projects` `p` ON jobs.projid = p.projid
JOIN `orders` `o` ON p.orderno = o.orderno
WHERE jobs.projid=:id
As #DCoder said: your select should now read select('jobs.*, p.orderno, p.category, o.bidno'). For consistency you should also alias jobs as follows
$rows = Yii::app()->db->createCommand()
->select('j.*, p.orderno, p.category, o.bidno')
->from('jobs j')
->join('projects p','j.projid = p.projid')
->join('orders o', 'p.orderno = o.orderno')
->where('j.projid=:id', array(':id'=>$id))
->order('j.jobno,j.projid')
->queryRow();
I think you should remove projects, orders from ->from('jobs, projects, orders') and may be you should lower the case of jobs.PROJID as your error message says that it couldn't find the column.