[英]Laravel ORM is giving an incorrect result on a simple query
實在不明白,幫我理解一下。
我正在編寫一個應用程序,其中包括計算 NFL 球隊“標記”(標記是贏/輸/平,對不起,我不知道英文單詞),所以我有一個“馬卡”屬性團隊模型,如下所示:
public function getMarcaAttribute() {
...
}
查詢非常簡單,首先我得到球隊作為本地人參加的比賽數量並計算勝利、失敗和平局,例如,這是勝利:
$gan += Juego::where('local', $this->id)
->where('score_local', '>', 'score_visitante')
->get()->count();
然后我以訪客的身份對游戲做同樣的事情,當然,倒置比較標志。
現在,讓我們看看亞特蘭大(25)的西雅圖(38)比賽,如果我在數據庫中做的話
SELECT COUNT(*) FROM juegos WHERE local='atl' AND score_local > score_visitante;
當然,它返回0。
在 ORM 中,生成的查詢是:
array (
'query' => 'select * from `juegos` where `local` = ? and `score_local` > ? and `score_local` is not null',
'bindings' =>
array (
0 => 'atl',
1 => 'score_visitante',
),
'time' => 0.89,
),
事情返回 1。我什至將->count()->get()
替換為->get()
並對結果執行foreach
:
$gan = Juego::where('local', $this->id)
->where('score_local', '>', 'score_visitante')
->get();
Log::info('Ganados');
foreach ($gan as $g) {
Log::info("$g->score_local > $g->score_visitante");
}
事情正在返回一行,上面寫着“25 > 38”
我真的不明白這里發生了什么。 任何的想法?
您可以使用whereRaw
實現這whereRaw
:
$gan = Juego::where('local', $this->id)
->whereRaw('score_local > score_visitante')
->get();
或者按照評論中的建議, whereColumn
:
$gan = Juego::where('local', $this->id)
->whereColumn('score_local', '>' , 'score_visitante')
->get();
@lagbox 在評論中找到了答案。 問題是通過使用帶有綁定的准備好的語句,術語score_visitante
不會被視為列名而不是字符串。
有幾種方法可以解決:
whereColumn
方法whereColumn
:$gan += Juego::where('local', $this->id)
->whereColumn('score_local', '>', 'score_visitante')
->count();
whereRaw
方法whereRaw
:$gan += Juego::where('local', $this->id)
->whereRaw('score_local > score_visitante')
->count();
DB::raw
:$gan += Juego::where('local', $this->id)
->where('score_local', '>', \DB::raw('score_visitante'))
->count();
注意:在
->count()
之前也不需要->get()
->count()
。 您可以指示數據庫進行計數。 當預期結果是包含多行的大型數據集時,這特別有用,通過僅返回一個數字而不是可能保留數千甚至數百萬行來保留網絡資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.