如何在Laravel 5.2中编写此查询?

时间:2016-02-27 09:47:44

标签: php mysql laravel

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

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

我想根据这些条件查询用户:
1,显示有文章的用户,不显示没有文章的用户 2,文章包含两种类型,发表和未发表," 1"表示已发表,展示已发表的文章,未展示未发表的文章 每页显示3,30个用户。

像这样,它不对,怎么修改呢?

HomeController:

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);
    }

}

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

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

3 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:1)

  

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

试试这段代码:

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

答案 2 :(得分:0)

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

我希望这会对你有所帮助。