Yii: can't use LIMIT in a mysql query - php

I'm using Yii, and I want to select 5 rows from mysql starting from the third row.
For Example, I have these rows:
ID - NAME
1 - abc
2 - bcd
3 - hdf
4 - fgr
5 - gdf
...
and I want to select 5 rows, starting from the third row.
My code:
$rows = Users::model()->findAll(array(
'order' => 'id DESC',
'limit' => '3, 5'
));
The problem this selects nothing.

There is an offset parameter.
$rows = Users::model()->findAll(array(
'order' => 'id DESC',
'limit' => '5',
'offset' => '3'
));

Related

Laravel 5.2 - Delete duplicates from my query

i have a query like this:
$players = PostBalance::where('post_id', $post->id)->orderBy('id','desc')->get();
It work well and return array with all values, Post balances have fields:
ID
score
post_id
user_id
I would like Delete user_id duplicated AND get the max score value. for example if i have:
[0] = 'id' => 1 , 'score'=> 10, 'user_id'=> 1, 'post_id' => 1
[1] = 'id' => 2 , 'score'=> 20, 'user_id'=> 1, 'post_id' => 1
[2] = 'id' => 3 , 'score'=> 30, 'user_id'=> 1, 'post_id' => 1
[3] = 'id' => 4 , 'score'=> 40, 'user_id'=> 2, 'post_id' => 1
[4] = 'id' => 5 , 'score'=> 50, 'user_id'=> 2, 'post_id' => 1
[5] = 'id' => 6 , 'score'=> 60, 'user_id'=> 2, 'post_id' => 1
I would like delete duplicates user_id and get only the user_id with max score:
RESULT:
[0] = 'id' => 3 , 'score'=> 30, 'user_id'=> 1, 'post_id' => 1
[1] = 'id' => 6 , 'score'=> 60, 'user_id'=> 2, 'post_id' => 1
You can use groupBy() and max() method like this (note: this will not actually delete the duplicates from DB, but work for your query):
$result = PostBalance::groupBy('user_id')
->max('score');
For further reference, see Laravel Docs
Or if you want to order the results by score, you can do it like this:
$result = PostBalance::orderBy('score', 'desc')
->groupBy('user_id')
->get();
Note: To get max of group by, try to first run orderBy(), then run groupBy() on the query instead.
Hope this helps!

How can i select records from two tables in cake php(cake 2)

I am new to cake php . i have two tables
ce_landing
ce_stat
structure is
ce_stat
id keyword click
1 keyword1 24
2 keyword2 2
3 keyword3 6
ce_landing
id page_keyword
1 keyword1,check,keyword3
2 keyword2,usa,alphanumeric
i want to fetch all the records ce_landing.page_keyword is present in ce_stat.keyword. I am using this in my cake php model
public $hasMany = array(
'Stat' => array(
'className' => 'Stat',
'foreignKey' => 'keywor',
'dependent' => false,
'conditions' => array('Stat.keyword LIKE' => '%Landing.page_keywords%'),
'group' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
but this is generated sql query like
SQL Query: SELECT Stat.id, Stat.customer_id, Stat.account,
Stat.campaign_id, Stat.campaign, Stat.keyword,
Stat.ad_grp_id, Stat.ad_grp, Stat.impressions,
Stat.clicks, Stat.cost, Stat.qualityScore,
Stat.keywordState, Stat.date_from, Stat.date_to,
Stat.user_id, Stat.created, Stat.modified, Stat.keywor
FROM EB_adwords.ce_stats AS Stat WHERE Stat.keyword LIKE
'%Landing.page_keywords%' AND Stat.keyword =
('559f479a-82ac-4e3d-8c24-19b5c0a8011f')
so it returns null data because of AND Stat.keyword =('559f479a-82ac-4e3d-8c24-19b5c0a8011f') conditions.
Update
what i want to get all the records from ce_landing with total clicks according to keywords present . i.e for record 1 in ce_landing. i'll get the result
id page_keyword clicks
1 keyword1,check,keyword3 30
2 keyword2,usa,alphanumeric 2
You needs a SQL statement equivalent to:
SELECT ce_landing.id, ce_landing.page_keyword, SUM(ce_stat.click) AS total_clicks
FROM ce_landing
LEFT JOIN ce_stat
ON FIND_IN_SET(keyword,page_keyword)>0
GROUP BY ce_landing.id, ce_landing.page_keyword;
which does not easily translate to Cakephp's find method. Just use the query method to implement.
$this->Landing->query("SELECT Landing.id, Landing.page_keyword, SUM(ce_stat.click) AS total_clicks
FROM ce_landing AS Landing
LEFT JOIN ce_stat
ON FIND_IN_SET(keyword,page_keyword)>0
GROUP BY Landing.id, Landing.page_keyword;");

Order by specific field values in CakePHP

I have array $productsTop
(int) 0 => '6
(int) 1 => '4',
(int) 2 => '1',
(int) 3 => '2',
(int) 4 => '3',
(int) 5 => '5'
where 6 4 1 2 3 5 are id's of product table.
I want to display only 5 products from my products table but not order by ID ASC or DSC,
I want to order them by ID exactly like they are ordered in arrar so it can first show product ID 6, then ID 4... to ID 5.
Can anybody help please.
$productTop = [6,4,1,2,3,5];
$product = $this->Product->find('all', array(
'conditions'=>array('Product.id'=>$productTop),
'limit'=>5
));
In this way it shows me all products but ordered by their ID so instead of showing me:
6,4,1,2,3,5
it shows:
1,2,3,4,5,6
You can order by specified values like this:
'order' => "FIELD(id, '6', '4', '1', '3', '2', '5')"
You can add like this. :)
->order(["FIELD(Product.id, '228')"=>'DESC', "Product.id"=>'DESC'])

CakePHP SQL conversion - basic ORDER BY

I have a table where I'd like to get all id's that equal 26 first, then have the rest sorted in descending order, so something like:
row id
--- --
1 26
2 26
3 26
4 27
5 25
6 24
Would normally result in:
select id
from table
order by id=26 desc, id desc
How should I construct a find() in Cake? This is what I figure:
$this->Model->find('all', array(
'conditions' => array('Model.id' => 26),
'order' => array('Model.id' => 'DESC')
));
But how should I tell Cake to retrieve the rest of the id's and sort them in descending order after retrieving all id's that equal 26?
Try this.
$this->Model->find('all', array(
'order' => array('Model.id = 26 DESC' , 'Model.id DESC')
));
Assuming that your id field is your primaryKey as defined by the CakePHP conventions, the query you have will only ever return one result. Thus the ordering is not relevant here.
I would also suggest using find('first') to prevent you getting a single result indexed numerically.
$this->Model->find('first', array('conditions' => array('id' => $id)));
If you wanted to return this single record, and then all the other records, I would inverse this with a find('all').
$this->Model->find('all', array('conditions' => array('id !=' => $id)));

Preventing associated queries on a hasMany model with find

I have a model that has several hasMany associations to other models. One thing I have noticed is that when I make a query against the parent table, all of the associated tables are queried as well. For performances sake, I would like to prevent this, as I do not need this data on every call to the parent model.
This is my current parent model:
class UserEntity extends UserAgentAppModel {
var $name = 'UserEntity';
var $primaryKey = 'entity_id';
var $actsAs = array('EavEntity');
var $validate = array(
'user_name'=>array(
'rule'=>'isUnique',
'message'=>'This username has already been taken. Please try again'
),
'user_pass' => array(
'rule' => array('between', 8, 16),
'message' => 'Passwords must be between 8 and 16 characters long.')
);
var $hasMany = array(
'UserEntityVarchar' => array(
'className' => 'UserEntityVarchar',
'foreignKey' => 'entity_id',
'isEav' => 'true'
),
'UserEntityDatetime' => array(
'className' => 'UserEntityDatetime',
'foreignKey' => 'entity_id',
'isEav' => 'true'
),
'UserEntityInteger' => array(
'className' => 'UserEntityInteger',
'foreignKey' => 'entity_id',
'isEav' => 'true'
),
'UserEntityBoolean' => array(
'className' => 'UserEntityBoolean',
'foreignKey' => 'entity_id',
'isEav' => 'true'
),
'UserEntityArray' => array(
'className' => 'UserEntityArray',
'foreignKey' => 'entity_id',
'isEav' => 'true'
)
);
);?>
This is what I am seeing in the query log. The issue I am seeing is that queries 12-17 always occur when using find. However, I am using a behavior to pull this data from my eav model.
1 SHOW FULL COLUMNS FROM `user_entities` 8 8 1
2 SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= 'latin1_swedish_ci'; 1 1 1
3 SHOW FULL COLUMNS FROM `user_entity_varchars` 4 4 1
4 SHOW FULL COLUMNS FROM `user_entity_datetimes` 4 4 1
5 SHOW FULL COLUMNS FROM `user_entity_integers` 4 4 1
6 SHOW FULL COLUMNS FROM `user_entity_booleans` 4 4 1
7 SHOW FULL COLUMNS FROM `user_entity_arrays` 4 4 1
12 SELECT `UserEntity`.`entity_id`, `UserEntity`.`user_name`, `UserEntity`.`user_pass`, `UserEntity`.`user_status`, `UserEntity`.`user_group`, `UserEntity`.`instance_id`, `UserEntity`.`is_logged_in`, `UserEntity`.`is_visible` FROM `user_entities` AS `UserEntity` WHERE 1 = 1 2 2 0
13 SELECT `UserEntityVarchar`.`value_id`, `UserEntityVarchar`.`attribute_id`, `UserEntityVarchar`.`entity_id`, `UserEntityVarchar`.`value` FROM `user_entity_varchars` AS `UserEntityVarchar` WHERE `UserEntityVarchar`.`entity_id` IN (1, 2) 3 3 0
14 SELECT `UserEntityDatetime`.`value_id`, `UserEntityDatetime`.`attribute_id`, `UserEntityDatetime`.`entity_id`, `UserEntityDatetime`.`value` FROM `user_entity_datetimes` AS `UserEntityDatetime` WHERE `UserEntityDatetime`.`entity_id` IN (1, 2) 0 0 0
15 SELECT `UserEntityInteger`.`value_id`, `UserEntityInteger`.`attribute_id`, `UserEntityInteger`.`entity_id`, `UserEntityInteger`.`value` FROM `user_entity_integers` AS `UserEntityInteger` WHERE `UserEntityInteger`.`entity_id` IN (1, 2) 0 0 0
16 SELECT `UserEntityBoolean`.`value_id`, `UserEntityBoolean`.`attribute_id`, `UserEntityBoolean`.`entity_id`, `UserEntityBoolean`.`value` FROM `user_entity_booleans` AS `UserEntityBoolean` WHERE `UserEntityBoolean`.`entity_id` IN (1, 2) 0 0 0
17 SELECT `UserEntityArray`.`value_id`, `UserEntityArray`.`attribute_id`, `UserEntityArray`.`entity_id`, `UserEntityArray`.`value` FROM `user_entity_arrays` AS `UserEntityArray` WHERE `UserEntityArray`.`entity_id` IN (1, 2) 0 0 0
22 SHOW FULL COLUMNS FROM `eav_attributes` 8 8 1
23 SELECT `EavAttribute`.`attribute_id`, `EavAttribute`.`attribute_code`, `EavAttribute`.`backend_model`, `EavAttribute`.`frontend_input`, `EavAttribute`.`frontend_label`, `EavAttribute`.`is_required`, `EavAttribute`.`is_user_defined`, `EavAttribute`.`is_unique` FROM `eav_attributes` AS `EavAttribute` WHERE `attribute_id` = 5 1 1 0
24 SELECT `EavAttribute`.`attribute_id`, `EavAttribute`.`attribute_code`, `EavAttribute`.`backend_model`, `EavAttribute`.`frontend_input`, `EavAttribute`.`frontend_label`, `EavAttribute`.`is_required`, `EavAttribute`.`is_user_defined`, `EavAttribute`.`is_unique` FROM `eav_attributes` AS `EavAttribute` WHERE `attribute_id` = 6 1 1 0
25 SELECT `EavAttribute`.`attribute_id`, `EavAttribute`.`attribute_code`, `EavAttribute`.`backend_model`, `EavAttribute`.`frontend_input`, `EavAttribute`.`frontend_label`, `EavAttribute`.`is_required`, `EavAttribute`.`is_user_defined`, `EavAttribute`.`is_unique` FROM `eav_attributes` AS `EavAttribute` WHERE `attribute_id` = 7
If you don't want to pull all the hasMany data in your find query set the value of recursive to -1 like in your controller
$results = $this->Model->find('all', 'recursive' => -1));
A better option is to use Containable behavior, this way you can specify which Models to fetch and which not. http://book.cakephp.org/view/1323/Containable
Do proper use of 'recursive' and 'unbind model' very good functionality of cake to restrict your query upto your useful data.
Check here how both works's you will get a better idea.

Categories