【问题标题】:How to exclude some rows based on user id in Laravel 5.4?如何在 Laravel 5.4 中根据用户 ID 排除某些行?
【发布时间】:2017-04-18 16:39:47
【问题描述】:

我有 3 张桌子:postsvotesusers。我想排除当前用户已经投票的帖子(Auth::user()->id)。我应该如何做到这一点?我试过这段代码:

 $user_id = Auth::user()->id;
        $posti = Post::with('user')
        ->whereDoesntHave("votes")
        ->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
        ->orderBy('posts.created_at', 'DESC')
        ->orderByVotes()
        ->take(20)
        ->get();

【问题讨论】:

  • 这将为您提供没有任何投票的帖子,而不是没有投票的用户。因此,对于那个 put where 条件,要使用用户 ID 在投票表中检查。

标签: mysql laravel eloquent laravel-5.4


【解决方案1】:

您可以使用投票关系和回调函数检查帖子是否没有来自登录用户的投票。要实现这一点,请使用以下代码:

$userId = Auth::user()->id;
Post::with('votes')
    ->whereDoesntHave('votes', function ($query) use ($userId) {
        $query->where('user_id', $userId);
    })
    ->get();

【讨论】:

    【解决方案2】:

    您还可以使用 if 条件中的关系来检查登录用户是否已经投票:

    $user = Auth::user()->id;
    @if($user->votes)
    
    @else
    

    【讨论】:

      猜你喜欢
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 1970-01-01
      • 2022-06-28
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多