【问题标题】:How to write this query in Laravel 5.2?如何在 Laravel 5.2 中编写此查询?
【发布时间】:2016-02-27 09:47:44
【问题描述】:

我正在使用 Laravel 5.2,如何编写这个查询?

有两个表,userarticles,它们是一对多的关系。

我想根据这些条件查询用户:
1、显示有文章的用户,不显示没有文章的用户。
2、文章分为已发表和未发表两种,“1”表示已发表,显示已发表文章,不显示未发表文章。
3、每页显示30个用户。

这样,不对,怎么修改?

主控制器:

public function index()
{
    $users = User::with('articles')->where('is_published','=',1)->paginate(30);
    return view('index', compact('users'));
}

用户:

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract

{
    use Authenticatable, CanResetPassword, HasRoleAndPermission;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function articles()
    {
        return $this->hasMany(Article::class);
    }

}

文章:

class Article extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    //edit-1:         
    //Scope a query to only include status=1.
    public function scopeStatus($query)
    {
        return $query->where('status',1);
    }

}

编辑:
@SSuhat @RamilAmr 谢谢!如果模型“文章”中有本地范围,如何修改答案:

$query = User::with(['articles' => function ($q) {
                $q->where('is_published', 1);
            }])
         ->has('articles') //<<<<<<<<<
         ->paginate(30);
return $query;

【问题讨论】:

  • “不正确”是什么意思?您能否发布您的 Eloquent 模型,这将是一个很大的帮助!
  • @JohnRoca Thansk。我已经发布了 Eloquent 模型。

标签: php mysql laravel


【解决方案1】:

试试这个:

$query = User::with(['articles' => function ($q) {
                $q->where('is_published', 1);
            }])->paginate(30);
return $query;

【讨论】:

  • 谢谢,如果用户没有文章,用户将不会显示,如何过滤?
【解决方案2】:

如果用户没有任何文章,则不会显示该用户,如何过滤?

试试这个代码:

$query = User::with(['articles' => function ($q) {
                $q->where('is_published', 1);
            }])
         ->has('articles') //<<<<<<<<<
         ->paginate(30);
return $query;

【讨论】:

    【解决方案3】:
    $query = User::with('articles')->wherehas('articles', function ($q) {
                $q->where('is_published', 1);
            })->paginate(30);
    return $query;
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2017-11-24
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      相关资源
      最近更新 更多