在Laravel中处理空洞的雄辩查询的最佳做法是什么?

时间:2017-07-18 14:34:19

标签: php laravel null eloquent

到目前为止,我正在使用eloquent的isset()和普通的php Sub vlookup2() Dim SourceLastRow As Long Dim OutputLastRow As Long Dim sourceSheet As Worksheet Dim outputSheet As Worksheet Set sourceSheet = Worksheets("Data1") Set outputSheet = Worksheets("Pivot") With sourceSheet SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row End With With outputSheet OutputLastRow = .Cells(.Rows.Count, "D").End(xlUp).Row .Range("*4:*" & OutputLastRow).Formula = _ "=VLOOKUP(D4,'" & sourceSheet.Name & "'!$A$2:$H$" & SourceLastRow & ",3,0)" End With End Sub ...

现在我正在使用他们两个......当一个人不能工作时我会切换到另一个然后它会起作用。

但是这会让代码看起来很脏.. 你有什么建议什么时候使用它们,有什么区别..在laravel中处理空洞的雄辩查询的最佳做法是什么..谢谢

1 个答案:

答案 0 :(得分:1)

我们可以使用empty()方法。

// After you initiate your model in variable
$var = Model::find($id);

// Just check it use empty method 
if(empty($var)) {
   // Do something here
}

修改 在最佳实践中使用原生exists()isset()的说明。

我们知道isset方法通常用于检查变量是否已定义。

$col = "column"
if(isset($col)) {
   // true
}
if(isset($cols)) {
   // else
}

对于使用exists(),通常用于验证。你可以在laravel文档中查看它。

$name = $request->get('name');
if(User::where('name', $name)->exists()){
  // It will true if the in users table exists the $name in name columns
  // And do something if true :D
} else {
  // If not exists/false you can return error like this

  return response()->json([
      'error'=>true
  ],400);
}