[英]Laravel dynamic where queries using Query Builder
我是Laravel的新朋友。 我想使用laravel查詢構建器動態查詢。
通常我可以在php中進行動態查詢
$where = array(
'hello' => 'world'
);
function get($where = null){
if($where == "") $where = "";
//Function which converts where clause into queries
wheretoqueries($where); //converts where clause
$sql = "SELECT * FROM $tbl $where";
return $sql;
}
echo get($where);
如果where子句為null,則查詢為
SELECT * FROM $tbl
如果where子句不為null,則查詢為
SELECT * FROM $tbl WHERE hello = "world"
如果鍵和值存在,Laravel Orm對於where子句工作正常
A::where($where)->get();
如果where為null,則以下方法將不起作用
嘗試這個。 如果$ where變量包含某些內容,則查詢將執行,否則它將從A
模型檢索所有數據。
function get($where = null){
if($where != null){
A::where('field_name', '=', $where)->first();
}else{
A::all();
}
}
注意:如果查詢返回多個值,則必須在查詢生成器的末尾使用get()方法,而不要使用first();。 參考: https : //laravel.com/docs/5.3/queries#where-clauses
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.