问题描述
我正在重构一个个人 Laravel 项目,但在改进它的过程中遇到了障碍。
函数是这样工作的:
1.从模型线程中获取集合
2. foreach 循环检查用户是否投票给那个线程,添加自定义键->值
3.返回集合
到目前为止,我一直在做的是:
线程控制器:
$threads = Thread::orderBy('created_at','desc')
->with('communities')
->with('author')
->withCount('replies')
->withCount('upVotes')
->withCount('downVotes')
->paginate(4);
foreach ($threads as $thread) {
if (Auth::user()) {
if (Vote::where('user_id','=',Auth::user()->id)->where('thread_id',$thread->id)->where('Vote_type',1)->exists()) {
$thread->user_has_Voted = 'true';
$thread->user_Vote_type = 1;
} elseif (Vote::where('user_id',0)->exists()) {
$thread->user_has_Voted = 'true';
$thread->user_Vote_type = 0;
} else {
$thread->user_has_Voted = 'false';
}
}
}
return $threads;
我想做的是这样的:
线程模型:
public function userVoteThread() {
if (Vote::where('user_id',Auth::user()->id)
->where('thread_id',$this->id)
->where('Vote_type',1)
->exists()) {
return $this->user_Vote_type = 1;
} elseif (Vote::where('user_id',0)
->exists()) {
return $this->user_Vote_type = 0;
}
}
线程控制器:
$threads = Thread::orderBy('created_at','desc')
->with('communities')
->with('author')
->with('userVoteThread') <----- ADDING NEW MODEL FUNCTION
->withCount('replies')
->withCount('upVotes')
->withCount('downVotes')
->paginate(4);
毕竟,我得到的最接近的是这个错误在 null 上调用成员函数 addEagerConstraints(),我一直在努力改进代码。
有没有办法让 Thread 模型函数工作并通过集合使用它?
非常感谢!
PS:我希望我让自己理解,否则,问我。谢谢:D
解决方法
首先给Thread模型添加关系。
class Thread {
public function votes() {
return $this->hasMany(Thread::class);
}
}
将您的 Eloquent Accessor 添加到线程。
class Thread {
public function getUserVoteTypeAttribute() {
$this->votes
->where('user_id',Auth::user()->id ?? -1)
->first()->user_vote_type ?? null;
}
public function getUserHasVotedAttribute() {
return $this->user_vote_type !== null;
}
}
现在您可以访问模型上的这些属性。
$thread = Thread::with('votes')->find(1);
$thread->user_vote_type;
$thread->user_has_voted;