Search code examples
phprelationshipphalconphalcon-orm

How to append sort by a field in phalcon relationship?


I have a situation where I want to sort my video blogs by recent upload and views i.e either sort by recent or sort by views. I tried the below code but now I have no idea what to do next?

$category = VideoBlogCategoryModel::getVideoBlogCategoryBySlug($categorySlug);
$category->getVideoBlogs(); // This is the relationship

Initialize function:

// Configure relation with VideoBlogModel
$this->hasMany('id', VideoBlogModel::class, 'category_id', array(
    'alias' => 'videoBlogs',
    'foreignKey' => true,
    'cxAction' => static::ACTION_CASCADE_DELETE,
    'params' => array(
        'order' => 'created_at DESC'
    )
));

How can I do something like $category->getVideoBlogs('order','views DESC') or $category->getVideoBlogs('order','created_at DESC') ?

From the initialize function you can see I already have an order param which is fetching the video blogs in descending order however I want it dynamic so that I can pass something like order by views as I mentioned above.

My Ajax:

// Sort By Recent and Views Feature
$('.cx_sort_video').change(function(e){
    // loading bar
    parameters.sort = $(this).val();
    ajaxLoadVideo(parameters);
});

Sort by dropdown:

<li class="list-inline-item">
    <span>SORT BY: </span>
    <select style="border:0px;" class="cx_sort_video">
        <option> RECENT</option>
        <option> VIEWS</option>
    </select>
</li>

Solution

  • You'll need to use getRelated(<relationshipName/Alias>, <array>parameters)

    $category->getRelated('videoBlogs', [
        'order' => 'created_at DESC'
    ]);