happy Coyote
happy Coyote

Reputation: 75

How do I get users last message using hasMany with laravel

Message Tables Column is

| messages_id(pk) | user_id | target_id | message | created_at

User_id has sender user's id. Target_id has receiver user's id

And simple user table has relation to MessageTable by HasMany.

public function message()
{
  return $this->hasMany('App\Model\TableModel\Message', 'user_id', 'user_id');
}

I want to get Userdata and each last message from user_id=[1,2,3,4] to target_id = 5.

So I tried this

User::WhereIn(user_id, [1,2,3,4])
     ->with(['message' => function ($query) {
          $query->Where('target_id', 5)->orderBy('messages_id', 'desc)->first();
        }])->get();
      

But this query return User's data and one user last message.

How do I get users last message using hasMany ?

Upvotes: 0

Views: 191

Answers (1)

OMR
OMR

Reputation: 12188

your hasMany relation is incorrect: the third argument should be the primary key of the current model:

public function message()
{
  return $this->hasMany('App\Model\TableModel\Message', 'user_id', 'id');
}

anyway, to get the last message, I recommend building a new relation using hasOne relation:

 public function lastMessage()
    {
      return $this->hasOne('App\Model\TableModel\Message', 'user_id', 'id')->latest();
    }

now, you can use this new relation like:

User::WhereIn(user_id, [1,2,3,4])
     ->with(['lastMessage' => function ($query) {
          $query->Where('target_id', 5);
        }])->get();

Upvotes: 2

Related Questions