2016-09-21 94 views
0

用戶記錄我有3個表:獲取關係

  1. users
  2. posts表(用戶可以有很多帖子)
  3. likes表(以同樣的方式,Facebook的喜歡做的工作)

我有以下關係:

user.php的

public function posts() 
{ 
    return $this->hasMany('App\Post'); 
} 

post.php中

public function user() 
{ 
    return $this->belongsTo('App\User'); 
} 

public function likes() 
{ 
    return $this->hasMany('App\Like'); 
} 

Like.php

public function post() 
{ 
    return $this->belongsTo('App\Post'); 
} 

要獲得所有的帖子,我做的:

$posts = Post::with('likes') 
    ->get(); 

但是,這返回全部喜歡與帖子相關(我不想)。我需要做的是檢查登錄用戶是否已經喜歡每個帖子。

例如,在我看來,我有:

@foreach ($posts as $post) 
    // check if logged in user liked the $post 
@endforeach 

如何修改我的代碼,這樣我可以檢查用戶是否喜歡每個崗位和我如何通過簡單地增加一個做到這一點新關係

+0

like和user之間沒有關係嗎? –

+0

@SanzeebAryal沒有,但如何幫助? – user6824515

+0

知道誰喜歡這個職位。 –

回答

0

首先,你需要創建用戶之間的關係,喜歡

用戶模型

public function likes() { 
    return $this->hasMany('App\Like'); 
} 

就像型號

public function user() { 
    return $this->belongsTo('App\User'); 
} 

郵政型號

public function isLiked() { 
    return (bool) $this->likes()->where('user_id', Auth::user()->id)->first(); 
    // Will return true if liked by the logged in user 
} 

現在你可以使用它像:

if ($post->isLiked()) { 
    // Do something 
} 
0

我敢肯定,你必須做出與喜歡之間的郵政聯繫,並與郵政用戶模型

所以......在郵政模式創建公共職能,我認爲你有像post_iduser_id等字段,以保持喜歡。

郵政型號:

public function likes() 
{ 
    return $this->belongsTo('App\Like', 'post_id); 
} 

後,在您的控制器化妝查詢來獲得職位

柱控制器

$post = Post::all(); 

,並在模板中,您可以檢查如果user_id在這篇文章中就像

帖子查看

foreach($post as $p) { 
    if($logged_user_id === $p->like()->user_id) { 
    echo 'liked'; 
    } else { 
    echo 'not liked'; 
    } 
} 
0

我認爲這會幫助你,(步驟1)

$post = Post::with(['Like.User' => function ($query) { 
     $query->where('users.id', '=', Auth::user()->id); 
    }])->get();  

注: - 用戶是表名。 它會給所有的帖子和所有喜歡的用戶登錄。

另一個解決方案,它會返回與用戶的特定喜歡(喜歡由auth用戶)的所有帖子。 (步驟-2)

 foreach ($post as $item) { 
     $like = $item->Like; 
     foreach ($like as $key => $user){ 
      if(count($user->User) == 0){ 
       unset($like[$key]); 
      } 
     } 
    }   

其結果將是對步驟1: -

 [ 
     { 
     "post" : "details", 
     "like" : [ { 
        "post_id" : 1, 
        "user_id" : 1 }, 
        { 
        "post_id" : 1, 
        "user_id" : null }], 
     { 
     "post" : "details", 
     "like" : [] } 
    ] 

其結果將是對步驟2: -

 [ 
     { 
     "post" : "details", 
     "like" : [ { 
        "post_id" : 1, 
        "user_id" : 1 }], 
     { 
     "post" : "details", 
     "like" : [] } 
    ]   

結果關鍵字是假設,並期望是在post和like表中使用user_id,在like表中使用post_id。