尋找改進的答案
在 Laravel 中,我使用的是原始查詢。我的問題是如何根據變數值添加 where 子句
即如果$cid存在那么查詢應該是
select * from user where aid=2 and cid=1;
如果它不存在
select * from user where aid=2;
理想情況下,我可以這樣做
if($cid) {
$query = DB::select("select * from user where aid=2 and cid=1");
} else {
$query = DB::select("select * from user where aid=2");
}
如果沒有上述方法,有沒有辦法做到這一點?
uj5u.com熱心網友回復:
這可以通過條件從句來實作。
$users = DB::table('users')
->where('aid', 2)
->when($cid, function ($query) {
$query->where('cid', 1);
})
->get();
uj5u.com熱心網友回復:
請把你的問題很好地結合起來,我們不知道你在說什么樣的情況,也不知道你的問題是在什么意義上被問到的。
通常上面的評論就足夠了,但有必要指定
以下是檔案中的一些示例
$users = DB::table('users')
->where('votes', '=', 100)
->where('age', '>', 35)
->get();
$users = DB::table('users')->where('votes', 100)->get();
您還可以將一組條件傳遞給 where 函式。陣列的每個元素都應該是一個陣列,其中包含通常傳遞給 where 方法的三個引數:
$users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
我鼓勵您閱讀關于此主題的非常清楚的檔案,并在 此處出現誤解時與我聯系
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432535.html
