Laravel雄辩地处理回调吗?
我想按时间过滤相关的用户详细信息。我的问题如下:Laravel雄辩地处理回调吗?,laravel,eloquent,closures,Laravel,Eloquent,Closures,我想按时间过滤相关的用户详细信息。我的问题如下: $employer = $user->organizations->where('status', true) ->where('start_date', '<=', date("Y-m-d")) ->where(function ($query) { $query ->where('end_date', '>
$employer = $user->organizations->where('status', true)
->where('start_date', '<=', date("Y-m-d"))
->where(function ($query) {
$query
->where('end_date', '>=', date("Y-m-d"))
->orWhereNull('end_date');
});
$employer=$user->organization->where('status',true)
->其中('开始日期','=',日期(“Y-m-d”))
->或wherenull(“结束日期”);
});
我在没有回调的情况下得到结果,但当我引入回调以在结束日期前过滤数据时,我得到错误“explode()希望参数2是字符串,对象给定”
应该如何重构此函数以获得结束日期为空或将来为空的组织?您应该返回关闭函数 试试这个:
$employer = $user->organizations->where('status', true)
->where('start_date', '<=', date("Y-m-d")->toDateTimeString())
->where(function ($query) {
return $query
->where('end_date', '>=', date("Y-m-d")->toDateTimeString())
->orWhereNull('end_date');
});
$employer=$user->organization->where('status',true)
->其中('start_date','=',date(“Y-m-d”)->toDateTimeString())
->或wherenull(“结束日期”);
});
根据上面的评论,我将代码重构为以下内容:
$employer = $user->organizations()->where('organization_user.status', true)
->where('organization_user.start_date', '<=', date("Y-m-d"))
->where(function ($query) {
$query
->where('organization_user.end_date', '>=', date("Y-m-d"))
->orWhereNull('organization_user.end_date');
})->get();
$employer=$user->organizations()->其中('organization\u user.status',true)
->其中('组织\用户.开始\日期','=',日期(“Y-m-d”))
->orWhereNull(“组织\用户.结束\日期”);
})->get();
我想你忘了获取数据。如果此代码段正确,则$employer
变量是生成器类,而不是集合。尝试使用->get()
。顺便说一句,$user->organizations
是illumb\Database\elount\Collection
。在这种情况下,您不是在数据库中搜索。如果要在数据库中搜索(以获得更好的性能),请使用$user->organizations()
方法,而不是属性。您应该将日期转换为字符串,并指定对象