Reputation: 418
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
Upvotes: 1
Views: 751
Reputation: 33058
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;
}
Upvotes: 4