1

I'm trying to create multi-participant messaging system. Here's the database design I'v found here: Messaging system database schema

Conversation
------------
id

Messages
--------
id
conversation_id
from_id
subject
message
from_timestamp

Participants
------------
conversation_id
user_id
last_read_timestamp

Could you help me to describe Eloquent relations between these models? I mean this: http://laravel.com/docs/eloquent#relationships

Community
  • 1
  • 1
Alex
  • 418
  • 4
  • 13

1 Answers1

4
class Conversation extends Eloquent
{
    public function messages()
    {
        return $this->hasMany('Message');
    }

    public function participants()
    {
        return $this->hasMany('Participant');
    }
}

class Message extends Eloquent
{
    public function conversation()
    {
        return $this->belongsTo('Conversation');
    }

    public function from()
    {
        return $this->belongsTo('User', 'from_id');
    }
}

class Participant extends Eloquent
{
    public function conversations()
    {
        return $this->belongsTo('Conversation');
    }

    public function user()
    {
        return $this->belongsTo('User');
    }
}

// Messages 
foreach($conversation->messages as $message)
{
    echo 'From: '.$message->from->username."<br />";  // Taking a guess here, depends on your user model.
    echo 'Subject: '.$message->subject."<br />";
    echo 'Message: '.$message->message."<br />";
    echo 'Timestamp: '.$message->from_timestamp."<br />";
    echo '<hr />';
}

// Participants
foreach($conversation->participants as $participant)
{
    echo 'User: '.$participant->user->username;
}
user1669496
  • 32,176
  • 9
  • 73
  • 65
  • Could you please check this? Am I doing it correct? https://gist.github.com/AleksMeshkov/59a26a86079cc722e900 – Alex Oct 11 '13 at 22:32