Define Laravel Eloquent relations between 3 models in a messaging system

我只是一个虾纸丫 提交于 2020-01-16 00:47:31

问题


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:


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;
}


来源:https://stackoverflow.com/questions/19326950/define-laravel-eloquent-relations-between-3-models-in-a-messaging-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!