我有帖子,用戶以後可以保存這些帖子。我創建了這個關係,我可以很容易地保存或刪除它們。問題是我無法檢查帖子是否保存在前端。現在我編寫了一些代碼來處理這個問題,但似乎並不奏效。這裏是我的控制器代碼: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