Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Order/Sort parent based on Childrens #12

Open
Aniket-IN opened this issue Aug 25, 2023 · 2 comments
Open

Order/Sort parent based on Childrens #12

Aniket-IN opened this issue Aug 25, 2023 · 2 comments

Comments

@Aniket-IN
Copy link

In my application,
I have MessageThread and Message model.

This is the migration for message_threads table:

            $table->string('sender_number', 15);
            $table->string('receiver_number', 15);

            $table->string('sender_number_receiver_number', 30)->virtualAs('CONCAT(`sender_number`, "-", `receiver_number`)');
            $table->string('receiver_number', 30)->virtualAs('CONCAT(`receiver_number`, "-", `sender_number`)');

            $table->string('contact_name', 75)->nullable();
            $table->unique(['sender_number', 'receiver_number']);

And messages

            $table->string('from', 15);
            $table->string('to', 15);

            $table->string('from_to', 30)->virtualAs('CONCAT(`from`, "-", `to`)');
            $table->string('to_from', 30)->virtualAs('CONCAT(`to`, "-", `from`)');

            $table->text('text')->nullable();

With that, I have relations like this in MessageThread:

    public function messages(): HasManyMerged
    {
        return $this->hasManyMerged(Message::class, ['from_to', 'to_from'], 'sender_number_receiver_number');
    }

It works fine, I mean I can get all messages (incoming, outgoing) from a message thread.

But I want to get a list of Threads, based on Messages.
Like, Thread which has most recent message should be on top, and least recent thread to the bottom.

I'm sure it's not the best solution for messaging, seems too hacky, but this is what I could come up with.
Please suggest some way to sort the threads, or maybe suggest something different all together.

Thanks.

@korridor
Copy link
Owner

Thanks for the issue. To be honest, currently I can only come up with trickier solutions with subqueries.
But it might be possible to get a very clean solution with the HasOne feature request in the following issue: !11

I hope I find the time to look into that in the following weeks, but I'm not so sure. If you are motivated, you can also provide a PR for the HasOne relation suggestion.

@korridor
Copy link
Owner

@Aniket-IN Please check out if !13 resolves your problem. It is currently not perfect and I'll add more tests, but I think it is stable enough to test the use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants