douzhi3454 2016-02-27 09:47
浏览 53

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

I am using Laravel 5.2 ,how to write this query?

There are two tables,user and articles,they have a one-to-many relationship.

I want to query users according to these conditions:
1、Show users who have articles,not show users who have not articles.
2、Articles contain two types,published and not published, "1" indicates published,show published articles ,not show articles which not published.
3、30 users are shown per page.

Like this, it's not right ,how to modify it?

HomeController:

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

User:

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

}

Article:

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

}

edit:
@SSuhat @RamilAmr Thanks! If there is a Local Scope in Model "Article",how to modify the answer:

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

3条回答 默认 最新

  • dongmei8209 2016-02-27 09:57
    关注

    Try this:

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

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系