我有一个问题,当我查询数据库并获得零结果时,我得到一个空数组,但我想抛出'ModelNotFoundException'。这是我的示例代码:
<?php
#App\Http\Controller\MainController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Demo;
use DB;
class MainController extends Controller
{
public function getTagRecords($tag, $limit)
{
try{
$results = Demo::getRecordsByTag($tag, $limit);
}catch (Illuminate\Database\Eloquent\ModelNotFoundException $e){
return response()->json(['message'=>'hello there error'], 404);
}
return $results;
}
我正在通过AJAX发送请求,并希望返回错误消息和状态。我没有修改过Handler类。
以下是型号代码:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use DB;
class Demo extends Model
{
public static function getRecordsByTag($tag, $limit)
{
$params = [
'tag' => $tag,
'limit' => $limit,
];
return DB::select("SELECT d.idDemo, d.idUsuario, u.Referencia, d.Uri_fichero,
(SELECT Nombre FROM Edad_voz WHERE IdEdad_voz = d.IdEdad_voz) Edad_voz,
(SELECT Nombre FROM Tono_voz WHERE idTono_voz = d.idTono_voz) Tono_voz,
(SELECT Idioma_Variante FROM Idioma WHERE idIdioma = d.idIdioma) Idioma,
(SELECT Nombre FROM Genero WHERE idGenero = d.idGenero) Genero
FROM Demo AS d
INNER JOIN logs AS l ON d.idDemo = l.idElemento
INNER JOIN usuario AS u ON d.idUsuario = u.idUsuario
WHERE
l.accion = :tag AND
l.procesado = '0'
ORDER BY idDemo
LIMIT :limit;", $params);
}
}
答案 0 :(得分:1)
我会重写你的getRecordsByTag
函数,如果它是这样的话,请小心:
$result = DB::select("SELECT d.idDemo, d.idUsuario, u.Referencia, d.Uri_fichero,
(SELECT Nombre FROM Edad_voz WHERE IdEdad_voz = d.IdEdad_voz) Edad_voz,
(SELECT Nombre FROM Tono_voz WHERE idTono_voz = d.idTono_voz) Tono_voz,
(SELECT Idioma_Variante FROM Idioma WHERE idIdioma = d.idIdioma) Idioma,
(SELECT Nombre FROM Genero WHERE idGenero = d.idGenero) Genero
FROM Demo AS d
INNER JOIN logs AS l ON d.idDemo = l.idElemento
INNER JOIN usuario AS u ON d.idUsuario = u.idUsuario
WHERE
l.accion = :tag AND
l.procesado = '0'
ORDER BY idDemo
LIMIT :limit;", $params);
if (is_empty($result)) throw new ModelNotFoundException;
return $result;
所以基本上:如果你的结果为空则抛出异常。您的控制器不需要对此进行任何修改。
答案 1 :(得分:0)
首先,您最好删除命名空间前的注释:#App\Http\Controller\MainController
第二,您可以并且应该检查该类是否存在,然后手动抛出异常
根据您使用的PHP版本,您应该能够执行以下操作:
if (class_exists(Demo::class)) {
$results = Demo::getRecordsByTag($tag, $limit);
} else {
// or you can throw an exception from here
// throw new Illuminate\Database\Eloquent\ModelNotFoundException('hello there error');
return response()->json(['message'=>'hello there error'], 404);
}
更新:我刚刚看到你提供了getRecordsByTag()方法调用背后的代码。我要说方法添加文档来解释它可以返回一个空的响应,例如array()
并且由调用者决定如何处理特定情况,使模型保持干净并且没有业务逻辑。因此在调用者中检查结果是否为空集合,如果是这种情况则抛出异常,因为它是其运行所需的特定逻辑。
if (count($results = Demo::getRecordsByTag($tag, $limit)) === 0) {
throw new RecordNotFoundException("Tag: $tag was not found in the Demo table");
}