Skip to content
This repository

Fields specified in relationships are ignored #635

danives opened this Issue · 1 comment

3 participants

Dan Ives Nate Abele Simon JAILLET
Dan Ives


I am trying to get a count of a related table with my query - however I do not know the correct way to do this. I tried specifying the field manually in the find:: method, but that returns only the field. I then thought I should do it using the relationships and specify the field in the relationship. This is a link to the example code I used:

However doing that, the 'fields' variable is ignored - as can be seen in the generated SQL. I tried recreating the SQL statement and adding the field in manually, but it seems lithium doesn't then know how to bind the data to a model:

If someone is able to help me with how to get an associated tables count, that would be fantastic.



Nate Abele


public $hasMany = array(
        'fields'=>array('count( as "count"'),

public function recent() {
    return Post::find('all',array('conditions'=>array('Post.published'=>1), "order"=>array('Post.created'=>'DESC'), "group"=>"", "with"=>array('User','Locations','Like','Dislike','CommentCount')));

// SQL generated

'SELECT * FROM `posts` AS `Post` LEFT JOIN `users` AS `User` ON `Post`.`author` = `User`.`id` LEFT JOIN `locations` AS `Locations` ON `Post`.`location` = `Locations`.`id` LEFT JOIN `likes` AS `Like` ON `Post`.`id` = `Like`.`post_id` LEFT JOIN `dislikes` AS `Dislike` ON `Post`.`id` = `Dislike`.`post_id` LEFT JOIN `comments` AS `CommentCount` ON `Post`.`id` = `CommentCount`.`post_id` WHERE Post.published = 1 GROUP BY ORDER BY Post.created DESC; '


$result = Post::find('all',array('fields'=>array('count('),'conditions'=>array('Post.published'=>1), "order"=>array('Post.created'=>'DESC'), "group"=>"", "with"=>array('User','Locations','Like','Dislike','Comment')));

// returns this
array(3) { [0]=> array(1) { ["id)"]=> string(1) "0" } [1]=> array(1) { ["id)"]=> string(1) "8" } [2]=> array(1) { ["id)"]=> string(1) "0" } }

$result = Post::find('all',array('fields'=>array('Post.*','count('),'conditions'=>array('Post.published'=>1), "order"=>array('Post.created'=>'DESC'), "group"=>"", "with"=>array('User','Locations','Like','Dislike','Comment')));

// returns this
array(3) { [0]=> array(2) { [""]=> array(1) { ["id)"]=> string(1) "3" } ["*"]=> string(1) "0" } [1]=> array(2) { [""]=> array(1) { ["id)"]=> string(1) "2" } ["*"]=> string(1) "8" } [2]=> array(2) { [""]=> array(1) { ["id)"]=> string(1) "1" } ["*"]=> string(1) "0" } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.