我尝试创建一个信使,用户可以在其中加入线程,因此我有四个表:
users
id - integer
name - string
threads
id - integer
name - string
created_at - dateTime
updated_at - dateTime
participants
user_id - integer
threads_id - integer
created_at - dateTime
updated_at - dateTime
deleted_at - dateTime
messages
id - integer
user_id - integer
thread_id - integer
text - string
created_at - dateTime
updated_at - dateTime
deleted_at - dateTime
用户:
threads(){
return $this->belongsToMany(
Thread::class,
'participants',
'user_id',
'thread_id'
)
->withTimestamps()
->withPivot('thread_id', 'user_id', 'deleted_at')
->orderBy('created_at', 'desc');
}
现在我尝试获取与消息的关系,只有加入线程后的消息应该是可见的:
public function messagesThroughThreads()
{
$relation = $this->hasManyThrough(
Message::class,
$this->threads(),
'user_id',
'thread_id',
'id',
'id'
)
->orderBy('updated_at', 'desc');
return $relation;
}
实际上,这不是那样的工作,我通过以下方式获得模型:
public function messagesThroughThreads(bool $show_deleted = false)
{
$messages = collect([]);
foreach ($this->threads as $thread){
if($thread->pivot->deleted_at){
$m = $thread->messages_model()->whereBetween('messages.created_at', [$thread->pivot->deleted_at, $thread->pivot->created_at])->get();
}else{
$m = $thread->messages_model()->where('messages.created_at', '>=', $thread->pivot->created_at)->get();
}
$messages = $messages->merge($m->toArray());
}
return $messages->unique();
}
任何想法如何获得具有相同条件的关系实例?
答案 0 :(得分:0)
没有(本机)关系直接访问消息。
根据您的数据,获取所有邮件然后删除其中一些邮件可能会更快:
class Thread
{
public function messages()
{
return $this->hasMany(Message::class);
}
}
public function messagesThroughThreads(bool $show_deleted = false)
{
$this->load('threads.messages');
foreach ($this->threads as $thread) {
$m = $thread->messages->where('created_at', '<=', $thread->pivot->deleted_at)
->where('created_at', '>=', $thread->pivot->created_at);
}
您将处理集合,因此whereBetween()
等方法无法使用。
答案 1 :(得分:0)
我创建了一个HasManyThrough
级的无限关系:Repository on GitHub
安装后,您可以像这样使用它:
class User extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function messagesThroughThreads() {
return $this->hasManyDeep(Message::class, ['participants', Thread::class])
->whereColumn('messages.created_at', '>=', 'participants.created_at')
->where(function($query) {
$query->whereNull('participants.deleted_at')
->orWhereColumn('messages.created_at', '<=', 'participants.deleted_at');
})->orderByDesc('messages.updated_at');
}
}