Define Laravel Eloquent relations between 3 models

2019-08-04 07:47发布

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

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-04 08:08
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;
}
查看更多
登录 后发表回答