本文介绍了在OR上下文中使用多个Laravel范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Subscription模型,在我的Laravel应用中包含开始日期
和 end_date
属性.我创建了两个查询范围scopeScopeActive和scopeFuture分别查找活动订阅和将来的订阅.
I have a Subscription model which contain start_date
and end_date
attributes in my Laravel app. I have created two query scopes, scopeActive and scopeFuture to find active and future subscriptions (respectively).
我想知道如何在OR上下文中使用两个范围来构建查询,以便可以找到任何活动的或将来的订阅.
I would like to know how I can build a query using both scopes in OR context, so that I can find any active or future subscriptions.
订阅模型
/**
* Scope a query to only include active subscriptions.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query)
{
return $query->where('start_date', '<', Carbon::now())
->where('end_date', '>', Carbon::now());
}
/**
* Scope a query to only include future subscriptions.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeFuture($query)
{
return $query->where('start_date', '>', Carbon::now());
}
public function business()
{
return $this->belongsTo('App\Business');
}
商业模式
.....
public function subscriptions()
{
return $this->hasMany('App\Subscription');
}
用户模型
public function business()
{
return $this->hasOne('App\Business');
}
控制器
Subscription::active()->get();
推荐答案
尝试一下.
$subscriptions = Subscription::where(function ($query) {
$query->active();
})->orWhere(function ($query) {
$query->future();
})->get();
评论中要求的示例
$subscriptions = auth()->user()
->business()
->subscriptions()
->where(function ($query) {
$query->active();
})->orWhere(function ($query) {
$query->future();
})->get();
这篇关于在OR上下文中使用多个Laravel范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!