我正在尝试使用多个嵌套的whereHas进行查询。
在我的数据库中,我有一个表'Ad',它有两种类型的子表;'Media'和'time_slot'的关系类型都是'hasMany'。
我想找到具有符合特定条件的time_slot子广告的父广告的媒体。这段代码已经解决了,但仍然工作:
$today = date('Y-m-d H:i:s');
$frm = "some string";
$media = Media::with('ad')
->whereHas('ad', function ($q) use ($today) {
$q->whereHas('time_slot', function ($q2) use ($today) {
$q2->whereDate('from', <=, $today)->whereDate('to', >=, $today);
});
})
->where('format', $frm)
->inRandomOrder()
->firstOrFail();
我已经重构并更正了您的查询:
$frm = "some string";
$media = Media::with('ad')
// here we use nested whereHas (relation1.relation2.relation3),
// it's easier to write and read
->whereHas('ad.time_slot', function($q){
// quotes added around the operator,
// it was probably causing you a syntax error
// I also used the now() helper, which will give you the
// same result as $today = date('Y-m-d H:i:s')
$q->whereDate('from', '<=', now());
$q->whereDate('to', '>=', now());
})->where('format', $frm)->inRandomOrder()->firstOrFail();
如果记录存在并且关系配置正确,它应该可以工作。