2017-12-18 237 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)後面添加 - 以查看爲什麼計數更大如果您預期它爲零,則爲零。什麼是返回? –

相關問題