2015-10-04 161 views
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 
+0

你可以做一個$ currentWeek的轉儲嗎?似乎沒有周財產。 – Tim

+0

我得到這個 集合{#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

+0

你不能使用魔術方法訪問屬性集合。爲了這個工作,你需要一個模型。如果您只需要一個結果,您可以使用 - > first()來替換 - > get()以直接接收模型。 – Tim

回答

1

因爲->get()返回對象的集合,您無法訪問propertys。爲了這個工作,你只需要你的雄辯模型的一個對象。

如果您只需要一個結果,您可以用->first()替換->get()以直接接收模型對象。