我只是在寻找一种更清洁的替代品,我无法在网上找到任何东西。
Timetable::where('weekday', '0')->update(['times' => $weekdays[0]]);
Timetable::where('weekday', '1')->update(['times' => $weekdays[1]]);
Timetable::where('weekday', '2')->update(['times' => $weekdays[2]]);
Timetable::where('weekday', '3')->update(['times' => $weekdays[3]]);
Timetable::where('weekday', '4')->update(['times' => $weekdays[4]]);
Timetable::where('weekday', '5')->update(['times' => $weekdays[5]]);
Timetable::where('weekday', '6')->update(['times' => $weekdays[6]]);
答案 0 :(得分:1)
你可以将它放在一个简单的for循环中,但这并不能使代码更清晰(更短)。看看Eloquent的范围功能。你可以这样做:
class Timetable extends Eloquent {
public function scopeWeekday($query, $day)
{
$query->where('weekday', $day);
}
public function updateTimes($weekday)
{
$data = array('times' => $this->weekdays[$weekday]);
$this->update($data);
}
}
我不知道$ weekdays中的数据是什么类型,但您可以使用此范围和更新方法,如下所示:
Timetable::weekday(1)->updateTimes(1);
我确实意识到这并不短,但它确实更清洁,更具可读性。您甚至可以将范围与更新结合起来,但我希望这能激发您清理代码。