对模型Laravel中的null自定义键调用成员函数addEagleConstraints()



我正在重构一个个人Laravel项目,但在改进它的过程中遇到了障碍。

功能是这样工作的:

1.从模型Thread中获取集合

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;

我想做的是这样的事情:

线程模型:

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);

毕竟,我得到的最接近的错误是在null上调用成员函数addEagleConstraints((,我一直在努力改进代码。

有没有办法让Thread模型函数工作并在集合中使用它?

非常感谢!

PS:我希望我能让自己理解,否则,请问我。谢谢:D

首先将关系添加到线程模型中。

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;
}
}

现在,您可以在模型上访问这些属性。

$thread = Thread::with('votes')->find(1);
$thread->user_vote_type;
$thread->user_has_voted;

最新更新