簡體   English   中英

Laravel動態在哪里使用查詢生成器查詢

[英]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查詢鏈接為:

$query = Model::query();

if (!empty($value)) {
   $query->where('column', $value);
}

$query->get();

要么

您可以將when方法用作:

Model::when($value, function ($query) use ($value) {
        return $query->where('column', $value);
    })
    ->get();

嘗試這個。 如果$ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM