我有帖子,用户以后可以保存这些帖子。我创建了这个关系,我可以很容易地保存或删除它们。问题是我无法检查帖子是否保存在前端。现在我编写了一些代码来处理这个问题,但似乎并不奏效。这里是我的控制器代码:Laravel试图检查用户是否与帖子有关系
$articleFlag = 1;
$userID = Auth::User()->id;
if (count($bestarticles) > 0) {
foreach ($bestarticles as $bestarticle) {
$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle);
if (count($saveddata) > 0) {
$articleFlag = 1;
} else {
$articleFlag = 2;
}
} //foeach endes here
} //first if endes here
,比我通过$articleFlag
到视图不是检查它与if
值但问题是,无论我做什么if (count($bestarticles) > 0)
返回true,我的观点获得价值1 。 有没有人知道我可能会错过什么?
这里是我的用户控制器relationshio:
function savedarticle(){
return $this->belongsToMany('App\User', 'savearticle', 'user_id',
'article_id');
}
,并在这里不用,我使用的保存和删除功能:
function savethearticle(Article $article){
$this->savedarticle()->syncWithoutDetaching([$article->id]);
}
function removethearticle(Article $article){
$this->savedarticle()->detach([$article->id]);
}
但你没有任何需要担心。我可以删除和添加。
还有另一种方法来检查视图中的现有关系或更好的方法来检查它在控制器中并进入视图?
我正在使用Laravel 5.4。
感谢您使它更具可读性。现在我的大脑不能很好地工作:/ – Nikonah
你可以发布你的'User'和'Article'模型,所以我们可以看到它们之间的关系。 – fubar
@fubar我加了。但是我可以删除和添加,这没有问题。我; m无法显示保存或删除按钮,取决于用户是否已经保存该帖子 – Nikonah