Home > Blockchain >  Cannot sort collection by relationship field
Cannot sort collection by relationship field

Time:06-28

I have a table called posts that stores all the post types, each post can have multiple and dynamic meta values, so I have the post_meta table which handle all of this.

The post_meta table have the following structure:

id | post_id |  meta_key | meta_value

This is the structure of the posts table:

id | content | type | created_at | updated_at | deleted_at

I need to order the post with the type section, so what I did so far is this:

$sections = Post::with('meta')->where([
    'type' => 'section',
    'language' => 'it',
    'status' => 'published',
])->get();

$sections->sortBy(function ($sec) {

    return $sec->getMeta('order')->meta_value;
});

where getMeta is a custom method that I have added within the Post model:

public function getMeta(string $metaKey)
{
    $key = array_search($metaKey, array_column($this->meta->toArray(), 'meta_key'));
    return $key !== false ? $this->meta[$key] : null;
}

The issue is that I doesn't get any ordering, what I'm doing wrong?

Current datasets:

id | type
 1   section
 2   section
 3   section

id | post_id | meta_key  | meta_value
 1     1        order       0
 2     2        order       2
 3     3        order       1

I should get this sequence: 1, 3, 2 instead of 1, 2, 3

CodePudding user response:

When you call sortBy on collection you don't modify the existing collection, so you need to do:

$sections = $sections->sortBy(function ($sec) {

CodePudding user response:

$sections = Post::with('meta')->where([
'type' => 'section',
'language' => 'it',
'status' => 'published',
])->get();

That Where clousure is not well executed, you need 3 parameteres per array to consult, like this:

$sections = Post::with('meta')->where([
['type' '=>' 'section'],
['language' '=>' 'it'],
['status' '=>' 'published'])->get();

And i'm not pretty sure what's the query builder you are trying to build because to me it looks like more like an assignation with those arrows.......whatever but at least you have the correct format now.

  • Related