我正在使用Laravel 5.2,如何编写此查询?如何在Laravel 5.2中编写此查询?
有两个表,user
和articles
,它们有一对多的关系。
我想根据这些条件查询用户:
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);
}
}
编辑:
@SSuhat @RamilAmr谢谢!如果在模型局部范围“文章”,如何修改答案:
$query = User::with(['articles' => function ($q) {
$q->where('is_published', 1);
}])
->has('articles') //<<<<<<<<<
->paginate(30);
return $query;
你是什么意思“这是不对的”?你可以发布你的雄辩模型,这将是一个很大的帮助! –
@JohnRoca Thansk.I发布了雄辩的模型。 – sunshine