I have two tables menus and lang_menus. My Menus model is as follows :
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'menulanguages'=>array(self::HAS_MANY, 'MenuLangs', 'menuId'),
);
}
...
public function getMenus(){
$criteria = new CDbCriteria();
$criteria->condition = "t.clientId = ".Yii::app()->user->clientId." AND menulanguages.languageId = ".Yii::app()->user->userlanguage;
$count = Menus::model()->with('menulanguages')->count($criteria);
$pages=new CPagination($count);
//Results per page
$pages->pageSize=10;
$pages->applyLimit($criteria);
$menus = Menus::model()->with('menulanguages')->findAll($criteria);
return array('menus' => $menus, 'paging' => $pages);
}
This is throwing the error Unknown column 'menulanguages.languageId'.
The error is in the line $menus = Menus::model()->with('menulanguages')->findAll($criteria);.
Surprisingly I am getting the value of the variable $count correctly.
On looking at the log I can see that the SQL query that is running for the findAll query is :
SELECT `t`.`id` AS `t0_c0`, `t`.`clientId` AS `t0_c1`, `t`.`restaurantId` AS `t0_c2` FROM `posif_menus` `t` WHERE (t.clientId = 1 AND menulanguages.languageId = 2) LIMIT 10
which means the join has not taken place. Whereas proper join query is running for the count value. Am I doing something wrong ?
Please help.
Just use together() of CActiveRecord or together property of CDbCriteria:
$menus = Menus::model()->with('menulanguages')->together()->findAll($criteria);
or:
$criteria = new CDbCriteria();
$criteria->condition = "t.clientId = ".Yii::app()->user->clientId." AND menulanguages.languageId = ".Yii::app()->user->userlanguage;
$criteria->together=true;
Try this.. apply joining table in cdbcriteria..
public function getMenus(){
$criteria = new CDbCriteria();
$criteria->condition = "t.clientId = ".Yii::app()->user->clientId." AND menulanguages.languageId = ".Yii::app()->user->userlanguage;
$criteria->with = array('menulanguages');
$count = Menus::model()->count($criteria);
$pages=new CPagination($count);
//Results per page
$pages->pageSize=10;
$pages->applyLimit($criteria);
$menus = Menus::model()->findAll($criteria);
return array('menus' => $menus, 'paging' => $pages);
}
Related
Hi I am new to Zend Framework. In normal php I know how to write queries. But in Zend Framework this is totally different.
I have written the query with left join and it is working fine but the thing is I want to get count of the joined table id. I will show my controller code:
controller:
$adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$projectTable = new TableGateway('blog', $adapter);
$rowset = $projectTable->select(
function(Select $select) {
$select->join(
array('b' => 'blog_answers'),
"b.question_id = blog.id",
array('new'=>COUNT('b.question_id'),'left')
);
}
);
while running this i am getting can you please clarify this how get the count.
HI this is the correct Query i got.
`
$adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$projectTable = new TableGateway('blog', $adapter);
$rowset = $projectTable->select(function(Select $select) {
$select->columns(array(
'*',
'num' => new Expression('COUNT(blog_answers.question_id)')
));
$select->join('blog_answers', 'blog.id = blog_answers.question_id', array(), 'left');
$select->group('blog.id');
});`
How can i findbypk with in condition
my query is
$model = User::model->findBypk($id);
now i want to apply In condition that UserRole should be in (1,2)
You can try this code :
$Criteria = new CDbCriteria();
$criteria->compare('id',$id);
$criteria->addInCondition('userRole', array (1,2));
$models = User::model()->findAll($Criteria);
You could use a criteria
criteria = new CDbCriteria();
$criteria->addInCondition('id', array(1,2));
$resultModels = User::model()->findAll($criteria);
The $resultModels return a collection of models that contain the required rows
Or if you want single model you can use find
criteria = new CDbCriteria();
$criteria->addInCondition('id', array(1,2));
$model = User::model()->find($criteria);
I have two tables store(id,name,date) and store_services(id,store_id,name,price,date)
I have implemented search filter by price, i wanted to show unique store records in my page.
But still i'm getting duplicate records from store table.
It's Working fine in mysql query by distinct(store_services.store_id)
but it's not working in Yii CDbCriteria.
my Mysql query is :
SELECT DISTINCT(store_services.store_id),store.id,store.name,store.date FROM store INNER JOIN store_services ON store.id = store_services.store_id WHERE store_service.price BETWEEN 1,1000
Please give me a code of Yii distinct records
NOTE: I'm using in Yii $criteria->distinct=true;
but it's also getting duplicate records
It's working replacing $criteria->distinct=true; to $criteria->group = 'store_id';
Here is my All code hope someone finding help from this.
$criteria=new CDbCriteria;
//$criteria->distinct=true;
$criteria->group = 'store_id';
$criteria->select = 't.id,t.name,t.state,t.city,t.location,t.address,t.contact_no,t.email,t.facilities,t.profile_photo,t.description, t.merchant_id, t.approve, t.added_date';
$flag = false;
if(isset($_GET['Store']['category']) && !empty($_GET['Store']['category'])){
$criteria->compare('mmmStoreServices.category_id', $_GET['Store']['category']);
$flag = true;
}
if(isset($_GET['Store']['sub_category']) && !empty($_GET['Store']['sub_category'])){
$criteria->compare('mmmStoreServices.service_id', $_GET['Store']['sub_category']);
$flag = true;
}
if(isset($_GET['Store']['price']) && !empty($_GET['Store']['price'])){
$price = explode('-',$_GET['Store']['price']);
$minPrice = trim($price[0]);
$maxPrice = trim($price[1]);
$criteria->addBetweenCondition('mmmStoreServices.price', $minPrice, $maxPrice);
$flag = true;
}
if($flag){
$criteria->with = array('mmmStoreServices'); // Put `mmm_store_service` to relations of model 'Store'
$criteria->together = true; // Check if you really need this parameter!
}
if(isset($_GET['Store']['location']) && !empty($_GET['Store']['location'])){
$criteria->compare('t.location', $_GET["Store"]["location"]);
//$flag = true;
}
$criteria->compare('t.approve', 'Y');
$ajaxModel = new CActiveDataProvider('Store', array(
'criteria' => $criteria,
'pagination' => array('pageSize'=>'2'),
));
I have such sql query
SELECT * FROM tbl_role WHERE
tbl_role.id NOT IN (
SELECT tbl_user_role.roleID FROM tbl_user_role
WHERE tbl_user_role.userID = 35
)
AND
tbl_role.id NOT IN (
SELECT tbl_user_role_request.roleID FROM tbl_user_role_request
WHERE tbl_user_role_request.userID = 35 AND tbl_user_role_request.dateEnd IS NULL)
What is the best solution to make it in Yii-like code. How can i do this query using Yii 1.x ?
Assumptions:
tbl_role has a model named Role
tbl_user_role has a model named UserRole
tbl_user_role_request has a model named UserRoleRequest
Note that this will do 3 seperate queries but I believe this is the closest you can get without creating a total mess.
<?php
$userId = 35;
$roles = UserRole::findAllByCondition(array('userId' => $userId));
$roleIds = array_values(CHtml::listData($roles, 'roleId', 'roleId');
$roleRequests = UserRoleRequest::findAllByCondition(array('userId'=>$userId, 'dateEnd'=>null));
$roleRequestIds = array_values(CHtml::listData($roleRequest, 'roleId', 'roleId'));
$criteria = new CDbCriteria();
$criteria->addNotInCondition('id', $roleIds);
$criteria->addNotInCondition('id', $roleRequestIds);
$roles = Role::findAll($criteria);
I would use CDbCommand: http://www.yiiframework.com/doc/api/1.1/CDbCommand#queryAll-detail
Use the following code to fetch the data
$data = Yii::app()->db->createCommand('sql query')->queryAll;
And then you can use this dataset to create the dropDownList
$list = CHtml::listData($data, 'value field', 'text field');
echo $form->dropDownList($model, 'attribute', $list);
I have following code to fetch data from a model.
$notifyModel = Notification::model()->findByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
Now I want to count the number of rows fetched.
Neither $notifyModel->count() work nor count($notifyModel).
It is very simple but googling did not help.
$notifyModels = Notification::model()->findAllByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
$count = count($notifyModels);
Or
$count = Notification::model()->countByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
the right usage of count():
$userid = Yii::app()->user->uid;
$count = Notification::model()->count( 'user_id=:userid', array(':userid' => $userid));
Please see http://www.yiiframework.com/doc/api/1.1/CActiveRecord#count-detail
try this:
$userid = Yii::app()->user->uid;
$notifyModel = Notification::model()->count(
array('condition' => 'user_id=:userid',
'params'=>array(':userid' => $userid)
));
$count = Notification::model()->countByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
Since the questions title is about calling the count function in a model I'll add some for those beginners reading this :)
A function inside a model could look like this:
/**
* Count the number of rows which match the user ID
* #param int $uid The user ID
* #return int The number of found rows
*/
public function getCountByUserID($uid)
{
$count = $this->count(array(
'condition'=>'user_id = :uid',
'params'=>array(
':uid'=>$uid,
),
));
return $count;
}
simple ways:
$model = News::model()->findAll(); //returns AR objects
$count = count($model);
I think it is much faster than others
$userTable=User::model()->tableName();
$userid = Yii::app()->user->uid;
$criteria=new CDbCriteria();
$criteria->select=count(id);
$criteria->compare('user_id',$userid);
$count=Yii::app()->db->commandBuilder->createFindCommand($userTable,$criteria)->queryScalar();
That method is wrong!
You trying to get by selecting all rows from database, you load the server, but that's wrong way!
All you need to do :
$sql = "SELECT COUNT(*) FROM {{...table_name...}}";
$count = intval(Yii::app()->db
->createCommand($sql)
->queryScalar());
Or you can create function in your model:
Class User extends CActiveRecord
{
private $_total;
public function getTotalItems()
{
if( empty( $this->_total )) {
$this->_total = intval(Yii::app()->db
->createCommand($sql)->queryScalar());
}
return $this->_total;
}
}
then you can use this functions like this:
$totalItems = User::model()->totalItems;
or :
$model = User::model()->findByPk( $uid );
$totalItems = $model->totalItems;
or :
$model = new User;
$totalItems = $model->totalItems;
This is the most simple way to do that:
$count = Table::Model()
->count("field=:field", array("field" => $fildID));
echo $count;
I strongly recommend you to find count with SQL query else it will degrade your system performance.
There are three way to find out count with the SQL query itself in Yii 1 CActiveRecord, those are:
1. count() method
Finds the number of rows satisfying the specified query condition.
Example :
$count = Notification::model()->count('user_id'=> Yii::app()->user->uid);
2. countByAttributes() method (available since v1.1.4)
Finds the number of rows that have the specified attribute values.
Example :
$count = Notification::model()->countByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
3. countBySql() method
Finds the number of rows using the given SQL statement. This is equivalent to calling CDbCommand::queryScalar with the specified SQL statement and the parameters.
Example:
$count = Notification::model()
->countBySql("select *from notification where user_id=:userId",
array(':userId'=>Yii::app()->user->uid)
);
Don't use the following code, which will reduce system performance:
$notifyModels = Notification::model()->findAllByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
$count = count($notifyModels);
Because, there are two function call to find the count
In my research, The easiest and Best Practice is like below.
$notifyModel = Notification::model()->count(array('user_id'=> Yii::app()->user->uid));