我目前正在使用Laravel博客App。我想显示帖子是由登录用户加入书签还是不在刀片模板视图上。
点击帖子的书签按钮,我调用ajax功能,这是正常的。
但是当我请求页面/posts
时,它会显示所有带有相同颜色书签的帖子
但未显示带红色的书签帖子书签按钮
我想区分帖子在页面呈现,如果它是由登录用户bookmared。
我在mysql数据库中有3个表:users
,posts
,bookmarks
表
结构用户表:( id,name,email,password,...)
结构帖子表:(id,title,body,user_id,...)
结构书签表:(user_id,post_id,created_at,updated_at)
这是用于在刀片视图中显示书签图标的代码
<span class="desktop-post-read-later">
@if(Auth::guest())
<span class="post-read-later" data-type="add" data-id="{{$post->id}}" title="Please login to bookmark this post!">
<i class="bookmark fa fa-bookmark-o" id="bookmark_{{$post->id}}"></i>
</span>
@else
<span class="post-read-later" data-type="add" data-id="{{$post->id}}">
@if( ????? what condition here i have to put ??????)
<i class="bookmark fa fa-bookmark-o" id="bookmark_{{$post->id}}" style="color:red"></i>
@else
<i class="bookmark fa fa-bookmark-o" id="bookmark_{{$post->id}}"></i>
@endif
</span>
@endif
答案 0 :(得分:1)
Auth::user()
返回当前登录的用户。
您的帖子表已有user_id
。您只需检查它是否与已登录用户的user_id相同:
@if($post->user_id == Auth::user()->id)
---------编辑----------
因此,您必须加入数据透视表才能知道已记录的用户是否已为帖子添加了书签:
原始查询:
select post.*, bookmarks.id as bookmarked from posts
left join bookmarks on bookmarks.post_id = posts.id and bookmarks.user_id = Auth::user()->id
使用查询构建器:
DB::table('post')->leftJoin('bookmarks', function($join) {
$join->on('post.id', '=', 'bookmarks.post_id');
$join->on('bookmarks.user_id', '=', DB::raw(Auth::user()->id);
})->select('post.*', 'bookmarks.id as bookmarked')
->get();
然后,使用@if
条件中的书签列。
答案 1 :(得分:0)
通过在PostsController
function get_user_bookmark_postids(){
$postsids=[];
if(Auth::check()){
$data = DB::table('posts')
->join('bookmarks', 'posts.id', '=', 'bookmarks.post_id')
->where('bookmarks.user_id', '=',Auth::user()->id)
->select('posts.id')
->get();
$plucked = $data->pluck('id');
$postsids=$plucked->all();
return $postsids;
}else{
$postsids=[];
}
}
public function index()
{
$bookmarked_posts=$this->get_user_bookmark_postids();
return view('user.posts.index',compact('bookmarked_posts'));
}
和刀片视图
<span class="desktop-post-read-later">
@if(Auth::guest())
<span class="post-read-later" data-type="add" data-id="{{$post->id}}" title="Please login to bookmark this post!">
<i class="fa fa-bookmark-o"></i>
</span>
@else
<span class="post-read-later" data-type="add" data-id="{{$post->id}}">
@if(in_array($post->id,$bookmarked_posts))
<i class="bookmark fa fa-bookmark-o" id="bookmark_{{$post->id}}" style="color:red"></i>
@else
<i class="bookmark fa fa-bookmark-o" id="bookmark_{{$post->id}}"></i>
@endif
</span>
@endif
</span>