如何检查数据库中的特定值并对其采取行动。 Laravel 4.2
How to check for specific value in database and act upon it. Laravel 4.2
我是 Laravel 的新手,我想知道如何检查数据库中的特定值?我的数据库中有 5 个不同的类别 ID,我想检查数据库并根据类别 ID 采取不同的操作。
我在想这样的事情:
if ($example = Example::where('category_id', '=', '1')->first()) {
echo "The category id is 1";
}
或者也许:
$example = Example::where('category_id', '=', Input::get('category_id'))->first();
if ($example === 1) {
echo "The category id is 1";
}
我也尝试了其他的东西,基于我已经在做的事情,但无法让这个功能发挥作用。
您可以像这样使用 Laravel 的 firstOrFail()
方法:
$example = Example::where('category_id', '=', '1')->firstOrFail();
if ($example) {
echo "The category id is {$example->id}";
}
return "error";
The firstOrFail
methods will retrieve the first result of the query;
however, if no result is found, a
Illuminate\Database\Eloquent\ModelNotFoundException
will be thrown
更新:
要获取和检查每一行,请使用 all()
方法并遍历每一行以获得所需的结果。
$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"
}
}
希望对您有所帮助!
我是 Laravel 的新手,我想知道如何检查数据库中的特定值?我的数据库中有 5 个不同的类别 ID,我想检查数据库并根据类别 ID 采取不同的操作。
我在想这样的事情:
if ($example = Example::where('category_id', '=', '1')->first()) {
echo "The category id is 1";
}
或者也许:
$example = Example::where('category_id', '=', Input::get('category_id'))->first();
if ($example === 1) {
echo "The category id is 1";
}
我也尝试了其他的东西,基于我已经在做的事情,但无法让这个功能发挥作用。
您可以像这样使用 Laravel 的 firstOrFail()
方法:
$example = Example::where('category_id', '=', '1')->firstOrFail();
if ($example) {
echo "The category id is {$example->id}";
}
return "error";
The
firstOrFail
methods will retrieve the first result of the query; however, if no result is found, aIlluminate\Database\Eloquent\ModelNotFoundException
will be thrown
更新:
要获取和检查每一行,请使用 all()
方法并遍历每一行以获得所需的结果。
$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"
}
}
希望对您有所帮助!