Question

Using the Lithium framework, I have two model classes, Post and Image. They are related via a hasMany relationship.

//Post.php
class Post extends \lithium\data\Model {
    public $hasMany = array('Image');
}

In one of my queries in my PostsController, I am attempting to find a Post with Images that are sorted by an order and have a limit. However the order and limit options on the Images are being ignored. Here is what my query looks like:

//PostsController.php
$post = Post::find('first', array(
    'with'=>array(
        'Image'=>array(
            'order'=>array('position'=>'ASC'),
            'limit'=>3
         )
     ),
    'conditions'=>array(
        'Post.id'=>'some-id-value'
    )
));

This particular query is returning the post with ALL of its related images, not sorted by 'position.' For example if this post had 10 images related to it, all 10 images are being returned with it instead of just the limit of 3, sorted by position.

In general, the idea is that I want to be able to order and limit a model's related hasMany data. Is this possible with the hasMany relationship in Lithium or will hasMany always return all the related data no matter what? Clearly what I am attempting is not the correct way of doing it.

Was it helpful?

Solution

Here's how you can use ORDER BY with Lithium Relationships ...

$table1_table2 = Table1::find('all', array(
    'conditions' => array('Table1.foo' => 'bar'),
    'with' => array('Table2'),
    'order' => array('Table2.title'),
    'limit' => 3
));

Note the 'Table2.title' which wll result in something like ...

SELECT ... ORDER BY Table2.title;

The ASC is implied in this case, but you can pass ASC or DESC as well.

OTHER TIPS

Do you can add a final query wich do you need? As I know, MySQL can't limit and order in JOINs at all, only in subqueries.

So, in this case, 2 requests is better than 1 join:

first Post::find(...conditions...) then

$images = Image::find(array(
   'order' => array('post_id','position'),
   'limit' => 3,
   'conditions' => array(
        'post_id' => $array_of_post_id_from_first_query
   )
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top