【发布时间】:2018-06-11 13:51:27
【问题描述】:
我正在尝试以下操作:我有两个通过 1xN 关系相关的模型(Pub 和 Schedule),如下所示:
酒馆:
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function pubSchedules()
{
return $this->hasMany(Schedule::class);
}
时间表:
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function pub()
{
return $this->belongsTo(Pub::class);
}
表计划具有以下字段:
标识 | pub_id |工作日 |开放时间 |关闭时间 |
我使用以下函数来了解一个酒吧当前是否(或未)开放:
/**
* @return bool
*/
public function isPubCurrentlyOpen()
{
$schedules = Schedule::where([
['pub_id', $this->id ],
['week_day', Carbon::now()->dayOfWeek],
])->get();
foreach ($schedules as $schedule){
$isOpen[] =
Carbon::now('Europe/Madrid')->between(
Carbon::now('Europe/Madrid')->setTimeFromTimeString($schedule->opening_time),
Carbon::now('Europe/Madrid')->setTimeFromTimeString($schedule->closing_time)
);
}
if(in_array(true, $isOpen)){
return true;
//return "Pub Opened";
}
return false;
//return "Pub Closed";
}
In my PubController I'd like, when the option "Filter by open pubs" is chosen if($request->openPubs == 1), to show only opened pubs isOpen ==true.
知道模型之间的关系,我该怎么做?
我正在寻找这样的东西:
if($request->openPubs == 1)
{
$pubs = $pubs->with('pubSchedules')->where('isOpen' == true);
}
你能帮帮我吗?
非常感谢!
【问题讨论】:
-
在模型中使用 $appends 和 getOpenPubs() 应该会为您提供您正在寻找的虚拟字段
标签: laravel orm eloquent filtering