yii Criteria only one row in result - php

I want to show some Calculated Values in CGridView, but it only shows ONE row in CGridView
The function:
public $Name;
public $ calculatedSum;
public function listSum()
{
$criteria = new CDbCriteria();
$criteria->select = 'Name as Name,'
. 'sum((wert1-wert2-wert3-wert4)*24) AS calculatedSum,'
return new CActiveDataProvider ( $this, array (
'criteria' => $criteria));
}
When I delete the AS calculatedSum part of the query it shows all results, but with the AS calculatedSum part it only shows one result in CGridView. But I need the AS calculatedSum to show the calculated Field in the view.
Anybody have an idea for a solution ?

$criteria->select = 'Name as Name,'
. '((wert1-wert2-wert3-wert4)*24) AS calculatedSum,'
Don't use the sum function. That sums up all columns, and without group by (which also isn't needed) will always cause you to have just one row. All you need is simple arithmetic, as you have inside the parenthesis.

Related

Cannot retrieve single column from database. Laravel

I'm trying to retrieve single column from my table grades.
For that I have used following code in my controller:
public function verify($id,$sid)
{
$grade=Grade::all('annual')->whereLoose('id',$id);
return $grade;
}
Where, annual is column name. But it is returning empty set of array [].
all() takes a list of columns to load from the database. In your case, you're fetching only one column called annual, therefore filtering on id later on does not return results. Replace your code with the following and it should work:
$grade = Grade::all('id', 'annual')->whereLoose('id', $id);
Keep in mind that it will return a collection of objects, not a single object.
NOTE: you're always loading all Grade objects from the database which is not efficient and not necessary. You can simply fetch object with given id with the following code:
$grade = Grade::find($id); // fetch all columns
$grade = Grade::find($id, ['id', 'annual']); // fetch only selected columns
The code you are using is loading all rows from the grades table and filtering them in code. It is better to let your query do the filter work.
For the columns part, you can add the columns you need to the first() function of the query, like so:
public function verify($id,$sid)
{
$grade = Grade::where('id', $id)->first(['annual']);
return $grade->annual;
}

select relations from MANY to MANY in yii framework using Criteria

I have a table Policy which links to another table Currency and the relation is as below:
'policyCurrency' => array(self::MANY_MANY, 'Currency', 'policy_currencies(PolicyId, CurrencyId)’),
I am also using the search function provided in the model to get the data and I want to select the Currency which resides in the related Currency Table as part of the search. Below is my search function.
public function search(){
$criteria = new CDbCriteria;
$criteria->compare('PolicyId', $this->PolicyId);
$criteria->compare('Name', $this->Name, true);
$criteria->compare('Amount', $this->Amount, true);
return new CActiveDataProvider($this, array( 'criteria' => $criteria));
}
When using the search getData:
$result = Policy->search()->getData();
The result returned is in the format of:
PolicyId = 1
Name = 'Test'
Amount = '20'
etc etc etc
I want the data related to the relations which is currency in this case be returned as part of the select like this (appending one after the other separated by a ',' since this is a MANY to MANY relation):
CurrencyId = 1,2,3
What I have tried:
Trying to use the
$criteria->with = array('policyCurrency');
$criteria->together = true;
but i am confused about how to use select to select all records from the first table Policy in my case and all related CurrencyIds seperated by a ',' from the related model.
Thanks
You need to add the relation name to the with attribute so it does a JOIN with Currency and gets all its related data:
public function search(){
$criteria = new CDbCriteria;
$criteria->with = array('policyCurrency');
For more info, check CDBCriteria documentation.

get count in relation table in yii2 Activerecord

I have two table for post and user. I want to show post count of user in users list gridview. In yii 1 I use this in model to define a relation for this purpose:
'postCount' => array(self::STAT, 'Post', 'author',
'condition' => 'status = ' . Post::ACTIVE),
...
User:find...().with('postCount').....
But i don't know how to implement this in Yii2 to get count of post in User:find():with('...') to show in gridview.
Anyone try this in yii2?
Here is an example of what I did and it seems to work fine so far. It was used to get a count of comments on a post. I simply used a standard active record count and created the relation with the where statement using $this->id and the primary key of the entry its getting a count for.
public function getComment_count()
{
return Comment::find()->where(['post' => $this->id])->count();
}
Just a passing it along...
You can try the code below:
User::find()->joinWith('posts',true,'RIGHT JOIN')->where(['user.id'=>'posts.id'])->count();
Or if you want to specify a user count:
//user id 2 for example
User::find()->joinWith('posts',true,'RIGHT JOIN')->where(['user.id'=>'posts.id','user.id'=>2])->count();
Please note that, posts is a relation defined in your User model like below:
public function getPosts()
{
return $this->hasMany(Post::className(), ['user_id' => 'id']);
}
Well still I think for those who it may concern, if you JUST want the count a select and not the data it will be better use this instead imho:
$count = (new \yii\db\Query())
->select('count(*)')
->from('table')
->where(['condition'=>'value'])
->scalar();
echo $count;

Table "tbl_category" does not have a column named "select"?

How to run 'OR' condition in model()->findByAttributes()?
This is my code:
$criteria->condition='url_title_en=:x OR url_title_da=:x';
$criteria->params=array(':x'=>$_GET['purl_title']);
$parentcat = Category::model()->findByAttributes($criteria);
But I'm getting this error:
Table "tbl_category" does not have a column named "select".
You can use OR like this
$criteria=new CDbCriteria();
$criteria->select='category_id';
$criteria->condition='url_title_en=:x';
$criteria->addCondition('url_title_da=:x','OR');
$criteria->params=array(':x'=>$_GET['purl_title']);
In above code addCondition appends the extra condition with OR operator. Now If you expect multiple records then you can use
$parentcat = Category::model()->findAll($criteria);
If you expect single record the you can use
$parentcat = Category::model()->find($criteria);
What you are using here that you are passing criteria to function FindByAttributes() which finds records with respect to attributes passed to it. Now you are passing it criteria and it finds first word as "select" because criteria translates your query like "select * where category_id=3". Now findByAttributes() take it as an attribute and tries to find it. thats why it shows error that tble_category cant find select.Here is official documentation of yii http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findAll-detail
The only problem with your code was that you were using findByAttributes instead of findAll.
$criteria = new CDbCriteria;
$criteria->condition = '`url_title_en` = :uri OR `url_title_da` = :uri';
$criteria->params = array(':uri' => $_GET['purl_title']);
$records = Category::model()->findAll($criteria);
// print all records fetched.
print_r($records);

How to select certain colums in yii CActive record?

I want to get all rows , certain columns using CActive record
I heard about findAll(); but it returns all rows, colums
$models = Users::model()->findAll();
How to get certain columns for example, only username, password for all users?
You can do with CDbCriteria
$criteria = new CDbCriteria;
$criteria->select = 't.username, t.password '; // select fields which you want in output
$models = Users::model()->findAll($criteria);
If you want the result in the form of array try this
$records= Yii::app()->db->createCommand()
->select('username,password')
->from('users')
->queryAll();
If as an object then kumar_v has already given an answer
the Kumar_v 's answer is completely correct, but if you want only username and password (or any two fields),
you can also use CHtml::listData() function like this :
$users=CHtml::listData(Users::model()->findAll(array('condition'=>'*condition*',
'limit'='*limit*')),"username", "password");
the $users is an array like this :
$users = array(
'username1'=>'password1',
'username2'=>'password2',
.
.
.
);
and of course you can access to a username's password simply by $users['username1']
You could use as usual sql query but getting so would not be in yii standard
So get findAll() and get the data that you want. that is proposed and best.

Categories