Support the ongoing development of Laravel.io →
Eloquent
Last updated 2 years ago.
0

how did you define the messages relationship in the user model ?

0

Hello Astroanu , I wold Like to first -

  • select all messages that users has added . A user hasMany() Messages as the message belongsTo() User .
  • After select the messages from that User , I wold Like to paginate it .

So I could display all the messages from that users , doing like that -

$all_messages_from_my_user = $this->user->Messages;

Ok , but I cant paginate it . I just can paginate if I do like this - Messages::orderBy('created_at', 'desc')->paginate(10);

But like this , I dont select the messages , from that users .

0

couldn't you use your original query

$messages = Messages::orderBy('created_at', 'desc')->paginate(10);

and in the foreach loop in the view, eager load the user

foreach ($messages as $message)
{
    echo $message->user->name;
}
0

hello w1n78 , but I want get just those messages from a user .

I can do it , like that , but Ithink that wold be not a good way , making 2 searches -

  • Fist I collect all IDs Messages , from that user .
  • After I make a new search with whereIn , like this -

Here I get all messages from a User

$messages = $this->user->Messages;

Collect all IDs

$display_items_id = array();
foreach ( $messages as $message){

       array_push($display_items_id , message->id );

}

Make a new search , now with those IDS that I found , AND finaly paginate it whith whereIn .

$get_all_messages_with_pagination = Message::whereIn('id' , $display_items_id )->paginate(20) ;

Some one know A betther way to do it ? I dont know if making 2 searches like this wold be a good approach .

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.