Reputation: 6034
This is what my table relationship is like:
One user may have multiple groups. One group may have multiple users. One message maybe be only by one user and group.
I have three models in laravel. User,Message, and Group. And my pivot table is mssg_group which stores which user sent which message to which group. (if this design is incorrect, do tell me the better way).
How do I write relationships to access all messages before a certain time by supplying a groupID?
Upvotes: 0
Views: 67
Reputation: 2401
I think your searching for the hasManyThrough relationship.
You need a Group model with a relationship to messages. See the Laravel Docs for more info.
/**
* app/Group.php
*/
public function messages(){
return $this->hasManyThrough('App\Message','App\MessageGroup');
}
In your Message Group Model you need to create the messages relation.
/*
* app/MessageGroup.php
*/
protected $table = "mssg_grp";
public function messages(){
return $this->hasMany('App\Message','id','mssg_id');
}
In your Message model be sure to define your custom table name.
/*
* app/Message.php
*/
class Message extends Model {
protected $table = 'mssg';
}
In your controller you can eager load the date requirement.
$group_messages = Group::where('id', $group_id)->with(function($query)
{
return $query->where('created_at','>',$date);
})->get()
I haven't tested it, so this may need to be tweaked a little bit, but it should get you close to where you want to be. I haven't address retrieving users, but it should be nearly the same as getting the messages synced up. Let me know if this helps.
Upvotes: 1