![](/img/trans.png)
[英]Laravel 8 - Call to a member function addEagerConstraints() on null
[英]Call to a member function addEagerConstraints() on null, custom key in model Laravel
我正在重构一个个人 Laravel 项目,但我在改进它的过程中遇到了阻碍。
function 是这样工作的:
1. 从 model 线程中获取一个集合
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', '=', Auth::user()->id)->where('thread_id', '=', $thread->id)->where('vote_type', '=', 0)->exists()) {
$thread->user_has_voted = 'true';
$thread->user_vote_type = 0;
} else {
$thread->user_has_voted = 'false';
}
}
}
return $threads;
我想做的是这样的:
螺纹 Model :
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', '=', Auth::user()->id)
->where('thread_id', '=', $this->id)
->where('vote_type', '=', 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);
毕竟,我得到的最接近的是这个错误Call to a member function addEagerConstraints() on null ,我一直在努力改进代码。
有没有办法让Thread model function 工作并通过集合使用它?
非常感谢!
PS:我希望我让自己明白,否则,问我。 谢谢:D
首先将关系添加到线程 model。
class Thread {
public function votes() {
return $this->hasMany(Thread::class);
}
}
将您的 Eloquent 访问器添加到线程。
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;
}
}
现在您可以在 model 上访问这些属性。
$thread = Thread::with('votes')->find(1);
$thread->user_vote_type;
$thread->user_has_voted;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.