2017-12-18 239 views
0

我有帖子,用户以后可以保存这些帖子。我创建了这个关系,我可以很容易地保存或删除它们。问题是我无法检查帖子是否保存在前端。现在我编写了一些代码来处理这个问题,但似乎并不奏效。这里是我的控制器代码: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。

+0

感谢您使它更具可读性。现在我的大脑不能很好地工作:/ – Nikonah

+0

你可以发布你的'User'和'Article'模型,所以我们可以看到它们之间的关系。 – fubar

+0

@fubar我加了。但是我可以删除和添加,这没有问题。我; m无法显示保存或删除按钮,取决于用户是否已经保存该帖子 – Nikonah

回答

1

看起来好像你有ArticleCollection模型,你要确定它是否是有关User与否。

如果是这种情况,当您最初查询Article模型时,我会建议急于加载User关系。这具有使用一个查询加载关系的优点,而不是每Article一个。

$userId = Auth::id(); 

$articles = Article::with(['savedarticle' => function ($query) use ($userId) { 
    return $query->where('user_id' => $userId); 
}])->get(); 

有了这个Collection,因为我们已经专门装目前已验证的User,进而你就可以知道,如果savedarticle关系有1一个count,该User关系存在。

foreach ($articles as $article) { 
    if ($article->savedarticle->count()) { 
     // User has already saved article 
    } else { 
     // User has not saved article 
    } 
} 
+0

这看起来像敏感的路要走,我会尝试它,如果它的工作原理 – Nikonah

+0

我与它玩了一下会标记为正确答案,做工精细 – Nikonah

+0

不客气。 – fubar

1

您是否应该在Where子句中传递bestarticle的id?另外,它需要一个 - > get()来将请求实际发送到数据库并运行查询。

$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle); 

应该

$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle->id)->get(); 
+0

是的,我想我错过了,但仍然无法正常工作。 – Nikonah

+0

仍然在视图中获得值1,这意味着该文章在执行时保存的不是 – Nikonah

+0

我会为该行添加一个 - > get(),然后在dd($ saveddata)后面添加 - 以查看为什么计数更大如果您预期它为零,则为零。什么是返回? –

相关问题