How to use IFNULL with yii CDbCriteria? - yii

In yii, i have a CDbCriteria with select property as:
$criteria->select = "IFNULL(t.cccid,'Default')";
That is I want to return 'Default' if t.cccid is NULL. Else value of t.cccid should be returned/
The problem is that IFNULL is not being recognized. I get error as:
trying to select an invalid column "'Default')"
I have also tried:
$criteria->select = "IFNULL(t.cccid,'Default') as cccid";
and then i get syntax error.
Can anyone help me on how to use IFNULL in $criteria->select?

Use of CDbExpression would help you here
$criteria->select = new CDbExpression("IFNULL(t.cccid,'Default') cccid");
or (to select * , or other columns, use array )
$criteria->select = array(
'*',
new CDbExpression("IFNULL(t.cccid,'Default') cccid"),
);

Related

Yii left join query

I want to execute the below sql query using Yii framework and need help on this.
SQL query
SELECT t.*, LP.name AS lp_name FROM `user` AS `t` LEFT JOIN `level_profiles` AS `LP` ON t.prof_i = LP.id WHERE t.bld_i IN (17)
So, i tried the below steps.
$usql = 't.bld_i IN (17)';
$criteria1 = new CDbCriteria;
$criteria1->select = 't.*, LP.*';
$criteria1->join = ' LEFT JOIN `level_profiles` AS `LP` ON t.prof_i = LP.id';
$criteria1->addCondition($usql);
$criteria1->order = 't.prof_i';
$result = User::model()->findAll($criteria1);
The above step is not allowing me to access the value from 'level_profiles' table.
Then, i tried to execute:
$usql = 't.bld_i IN (17)';
$result = User::model()->with('level_profiles', array(
'level_profiles'=>array(
'select'=>'name',
'joinType'=>'LEFT JOIN',
'condition'=>'level_profiles.id="prof_i"',
),
))->findAll($usql);
This is returning an error 'Relation "level_profiles" is not defined in active record class "User". '
I know this could be executed using the below method.
Yii::app()->db->createCommand('SELECT query')->queryAll();
But i dont want to use the above.
I am a beginner with Yii and tried to look into the forums. But, i am getting confused how to execute the query using "User::model()" approach .
class User extends CActiveRecord
{
......
public function relations()
{
return array(
'level_porfile_relation'=>array(self::BELONGS_TO, 'Level_Profiles_Modelname', 'prof_i'),
);
}
and your query will be:
$result = User::model()->with('level_porfile_relation')->findAll($usql);

How to get a single value in findbyPk() method in yii?

In my controller
$agent = University::model()->findByPK($university_id);
I hope it will return value of a row of value.
I want a single attribute(field3) value say university_name, (with out using findByPK), how to get it
SELECT field3 FROM table [WHERE Clause]
Try this
$usercriteria = new CDbCriteria();
$usercriteria->select = "university_name";
$usercriteria->condition = "university_id=$university_id";
$university = University::model()->findAll($usercriteria);
echo $university->university_name;
Or simply do like u did first
$agent = University::model()->findByPK($university_id);
echo $agent-> university_name;
$agent = University::model()->findByPK($university_id);
echo $agent->university_name;
It should be like this:
$agent = University::model()->findByPK($university_id)->university_name;
Try this:
$university_name = University::model()->findByPK($university_id, array('select'=>'univeersity_name'))->university_name;
#Query: SElECT university_name FROM table_name where id=x;
Instead of
$university_name = University::model()->findByPK($university_id)->university_name;
#Query: SElECT * FROM table_name where id=x;
Second query returns all the fields. So better to avoid those fields are not necessary.
in case if you need to view on the yii _views, i have implemented this on my project
i put this inside my '_view.php' at /protected/views/myTable/
$agent = University::model()->findByPK($data->id_university/*this is the PK field name*/);
echo $agent->university_name /*university field name*/;
sorry again for my bad english :o
It can be done like this:
$agent = University::model()->findAllByAttributes(array('field3'),"WHERE `id` = :id", array(':id' => $university_id));
First argument of findByAttributes is an array of attributes you wish it to return. If left empty it returns all (*).

Codeigniter Joining Tables - Passing Parameters

I'm attempting to join two tables while using codeigniter. I've done this same SQL query writing regular SQL. When I attempt to do the same in codeigniter, I keep getting errors. I'm not quite sure what I'm doing wrong. What do you guys think I'm doing wrong?
My function in model_data.php
function getJoinInformation($year,$make,$model)
{
//$this->db->distinct();
// here is where I need to conduct averages but lets just work on extracting info.
// from the database and join tables.
$this->db->select('*');
$this->db->from('tbl_car_description');
$this->db->join('tbl_car_description', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
/*
$query = $this->db->get_where('tbl_car_description',
array(
'year' => $year,
'make' => $make,
'model' => $model
)
);
if($query->num_rows()) return $query->result();
return null;
*/
}
My error message
A Database Error Occurred
Error Number: 1066
Not unique table/alias: 'tbl_car_description'
SELECT * FROM (`tbl_car_description`) JOIN `tbl_car_description` ON `d`.`id` = `p`.`cardescription_id` WHERE `d`.`year` = '2006' AND `d`.`make` = 'Subaru' AND `d`.`model` = 'Baja'
Filename: C:\wamp\www\_states\system\database\DB_driver.php
Line Number: 330
Here is the code written in SQL and it's working great. I want to do the something in codeigniter but I'm confused as to how. Any help would be much appreciated. Thanks everyone.
$sql_2 = mysql_query("SELECT ROUND(AVG(p.value),1) AS AvgPrice, ROUND(AVG(p.mileage),1) AS AvgMileage
FROM tbl_car_description d, tbl_car_prices p
WHERE (d.id = p.cardescription_id)
AND (d.year = '".$year."')
AND (d.make = '".$make."')
AND (d.model = '".$model."')
AND (p.approve = '1')");
Your CI query references the same table twice, which I assume is a typo. However, you only need include your table alias with the table name in your Active Record call:
//$this->db->distinct();
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
Couple issues: You need to include your table aliases and your join should have the name of the second table ...
$this->db->from('tbl_car_description AS d');
$this->db->join('tbl_car_prices AS p', 'd.id = p.cardescription_id');

codeigniter change complex query into active record

I have a codeigniter app.
My active record syntax works perfectly and is:
function get_as_09($q){
$this->db->select('m3');
$this->db->where('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['m3'])); //build an array
}
return $row_set;
}
}
This is effectively
select 'm3' from 'ProductList' where ProductCode='$1'
What I need to do is convert the below query into an active record type query and return it to the controller as per above active record syntax:
select length from
(SELECT
[Length]
,CONCAT(([width]*1000),([thickness]*1000),REPLACE([ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options
FROM [dbo].[dbo].[ProductList]) as p
where options='25100cr' order by length
I picture something like below but this does not work.
$this->db->select(length);
$this->db->from(SELECT [Length],CONCAT(([width]*1000),([thickness]*1000),REPLACE[ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options
FROM [dbo].[dbo].[ProductList]);
$this->db->where(options, $q);
$this->db->order(length, desc);
Help appreciated as always. Thanks again.
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available And now here is your query with active record
$select = array(
'Length'
'CONCAT(([width]*1000)',
'thickness * 1000',
'REPLACE(ProductCode, concat((width*1000),(thickness*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options'
);
$this->db->select($select);
$this->db->from('ProductList');
$Subquery = $this->db->_compile_select();
$this->db->_reset_select();
$this->db->select('length');
$this->db->from("($Subquery)");
$this->db->where('options','25100cr');
$this->db->order_by('length');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Source

How to get particular column in zend using Left join

I am new to zend framework,
Following is the plain mysql query which takes particular column from table,
SELECT jobs_users.id,jobs_users.first_name from jobs_users left join friends on jobs_users.id=friends.friend_id where friends.member_id=29
I tried with zend to implement the above query like below,
public function getFriendsProfileList($id){
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('jobs_users')
->joinLeft(
'friends',
'jobs_users.id=friends.friend_id',
array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo')
)
->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;
}
Here i got result with all column name , not with exact column name which i have given in query.
Kindly help me on this.
Use this instead:
$select->from('jobs_users', array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'))
->joinLeft('friends', 'jobs_users.id=friends.friend_id')
->where("friends.member_id = ?", '20');
You may also try this:
$select = $db->select();
$select->setIntegrityCheck(false);
$select->joinLeft('jobs_users','',array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'));
$select->joinLeft('friends','jobs_users.id=friends.friend_id', array());
$select->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;