0
我想将一个MySQL查询转换成Laravel雄虎查询。将MySQL查询转换成Laravel雄辩
下面的代码将选择结果的一排然后其返回WEEKNUM列
function currentWeek() {
$sql = "SELECT DISTINCT weekNum FROM schedule WHERE DATE_ADD(NOW(), INTERVAL -50 HOUR) < gameTimeEastern ORDER BY weekNum LIMIT 1 ";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$row = $query->fetch_assoc();
return $row['weekNum'];
}
}
的价值在Laravel在我SchedulesController这就是我想要的目的。
public function index()
{
$schedules = Schedule::where('week', '=', 4)->get();
return view('schedules.index', compact('schedules'));
}
很明显,我不想在这个星期内硬编码。这是我的尝试。
public function index()
{
$currentWeek = Schedule::distinct()
->where('gameTime', '<', Carbon::now()->addHours(100))
->orderBy('gameTime', 'desc')
->take(1)
->get();
$schedules = Schedule::where('week', '=', $currentWeek->week)->get();
return view('schedules.index', compact('schedules'));
}
但我得到这个错误
ErrorException in SchedulesController.php line 25:
Undefined property: Illuminate\Database\Eloquent\Collection::$week
你可以做一个$ currentWeek的转储吗?似乎没有周财产。 – Tim
我得到这个 集合{#157▼ #items:阵列:1 [▼ 0 =>附表{#158▼ #fillable:数组:15 [▶] #connection:空 #table:空 #primaryKey: “ID” #perPage:15 +递增:真 +时间戳:真 #attributes:数组:18 [▶] #original:数组:18 [▶] #relations:[] #hidden :[] #visible:[] #appends:[] #guarded:array:1 [▶] #dates:[] #dateFormat:空 #casts:[] #touches:[] #observables:[] #with:[] #morphClass:空 +存在:真 } ] } – locnguyen
你不能使用魔术方法访问属性集合。为了这个工作,你需要一个模型。如果您只需要一个结果,您可以使用 - > first()来替换 - > get()以直接接收模型。 – Tim