Php 如何检查数据库中的特定值并对其进行操作。拉威尔4.2

Php 如何检查数据库中的特定值并对其进行操作。拉威尔4.2,php,sql,laravel,laravel-4,Php,Sql,Laravel,Laravel 4,我对Laravel有点陌生,我想知道如何检查数据库中的特定值?我的数据库中有5个不同的类别id,我想对数据库进行检查,并根据类别id的不同采取不同的行动 我是这样想的: if ($example = Example::where('category_id', '=', '1')->first()) { echo "The category id is 1"; } $example = Example::where('category_id', '=', '1')->firs

我对Laravel有点陌生,我想知道如何检查数据库中的特定值?我的数据库中有5个不同的类别id,我想对数据库进行检查,并根据类别id的不同采取不同的行动

我是这样想的:

if ($example = Example::where('category_id', '=', '1')->first()) {
    echo "The category id is 1";
}
$example = Example::where('category_id', '=', '1')->firstOrFail();
if ($example) {
    echo "The category id is {$example->id}";
}
return "error";
或者可能:

$example = Example::where('category_id', '=', Input::get('category_id'))->first();
if ($example === 1) {
    echo "The category id is 1";
}
我还尝试了其他方法,基于我已经在使用的功能,但无法使用seam使此功能正常工作。

您可以使用类似以下的Laravel方法:

if ($example = Example::where('category_id', '=', '1')->first()) {
    echo "The category id is 1";
}
$example = Example::where('category_id', '=', '1')->firstOrFail();
if ($example) {
    echo "The category id is {$example->id}";
}
return "error";
firstOrFail
方法将检索查询的第一个结果; 但是,如果未找到结果,则 将抛出
illumb\Database\elount\ModelNotFoundException

更新:

要获取和检查每一行,请使用方法并遍历每一行以获得所需的结果

$examples = Example::all();
foreach($examples as $example) {
    if ($example->category_id == 1) {
        echo "echo here the 1 thing....";
    } elseif($example->category_id == 2) {
        echo "echo here the 2 thing....";
    } else {
        echo "something else"
    }
}

希望这有帮助

谢谢你的回复!这是朝着正确方向迈出的一步,然而,它并不能解决我的问题。此解决方案使每一行都回显类别id设置为1的行的id。因此,所有行最终都会回显类别id 1的id,无论它们的id是什么,结果是您想要什么,你能告诉我吗?例如,我想让category_id设置为1的每一行回显一件事,category_id设置为2的每一行回显一件事。现在,不管category id实际是什么,它都回显category id为1。非常感谢!这确实帮助我找到了正确的解决方案