【问题标题】:Where condition on multiple relations in laravelLaravel 中多个关系的条件
【发布时间】:2016-09-12 11:13:34
【问题描述】:

我在数据库中有三个表(即 Post、Comment、Like)。我想用评论和喜欢来获取那些帖子。但只有那些用户评论或喜欢的帖子。如果用户没有评论或喜欢,则不应获取帖子。我知道如何在不同的关系上获取有条件的数据。但我不明白如何在关系中使用 OR 条件。如果有人知道答案,将不胜感激。

这是我的个人关系条件代码。

$this->posts = Post::with(['comments', 'votes']);
if($field == 'comments') {
    $this->posts->whereHas('comments', function($query)
        {
            $query->where('in_user_id', Auth::user()->in_user_id);
        });
} else if ($field == 'votes') {
    $this->posts->whereHas('votes', function($query)
        {
            $query->where('in_user_id', Auth::user()->in_user_id);
        });
} else if($field == 'both') {
    // Here I want help
}

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    好吧,这是我的焦点错误。我只关注$query->where()。但这很简单。我只需要把whereHas()改成orWhereHas()就可以投票了。

    这里是更新的(解决方案)代码。

    $this->posts = Post::with(['comments', 'votes']);
    if($field == 'comments') {
        $this->posts->whereHas('comments', function($query)
            {
                $query->where('in_user_id', Auth::user()->in_user_id);
            });
    } else if ($field == 'votes') {
        $this->posts->whereHas('votes', function($query)
            {
                $query->where('in_user_id', Auth::user()->in_user_id);
            });
    } else if($field == 'both') {
        $this->posts->whereHas('comments', function($query)
            {
                $query->where('in_user_id', Auth::user()->in_user_id);
            });
        $this->posts->orWhereHas('votes', function($query)
            {
                $query->where('in_user_id', Auth::user()->in_user_id);
            });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2021-10-09
      • 2020-10-24
      • 2013-11-13
      • 2021-08-30
      相关资源
      最近更新 更多