php 检查 Laravel 模型是否已保存或查询是否已执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27877948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:35:11  来源:igfitidea点击:

Check if laravel model got saved or query got executed

phpmysqlvalidationlaravelmodel

提问by user2722667

I've seen alot of people using this way to check if a laravel model got saved. So now I wonder if it is a safe way.

我见过很多人使用这种方式来检查 laravel 模型是否被保存。所以现在我想知道这是否是一种安全的方式。

And also can I check if the queries bellow got executed like this

我也可以检查下面的查询是否像这样执行

Check if model got saved

检查模型是否已保存

Eg:

例如:

$myModel = new User();

$myModel->firstname = Input::get('firstname');
$myModel->lastname = Input::get('lastname');

$myModel->save();

//Check if user got saved
if ( ! $myModel->save())
{
  App::abort(500, 'Error');
}

//User got saved show OK message
return Response::json(array('success' => true, 'user_added' => 1), 200);

Is the above a safe way to check whenever my model got saved or not?

以上是检查我的模型是否被保存的安全方法吗?

Check if query returned a result

检查查询是否返回结果

Eg:

例如:

$UserProduct = Product::where('seller_id', '=', $userId)->first();

if (! $UserProduct)
{
    App::abort(401); //Error
}

Does above return an error if no product where found?

如果找不到产品,上面是否会返回错误?

Check if query got executed

检查查询是否被执行

Eg:

例如:

$newUser = User::create([
        'username' => Input::get('username'),
        'email' => Input::get('email')
]);

//Check if user was created
if ( ! $newUser)
{
    App::abort(500, 'Some Error');
}


//User was created show OK message
return Response::json(array('success' => true, 'user_created' => 1), 200);

Does above check if a user was created?

以上是否检查用户是否已创建?

回答by lukasgeiter

Check if model got saved

检查模型是否已保存

save()will return a boolean, saved or notsaved. So you can either do:

save()将返回一个布尔值,保存或保存。所以你可以这样做:

$saved = $myModel->save();

if(!$saved){
    App::abort(500, 'Error');
}

Or directly save in the if:

或者直接保存在if中:

if(!$myModel->save()){
    App::abort(500, 'Error');
}

Note that it doesn't make sense to call save()two times in a row like in your example. And by the way, many errors or problems that would keep the model from being saved will throw an exception anyways...

请注意,save()像您的示例中那样连续调用两次是没有意义的。顺便说一句,许多会使模型无法保存的错误或问题无论如何都会引发异常......

Check if query returned a result

检查查询是否返回结果

first()will return nullwhen no record is found so your check works find. However as alternative you could also use firstOrFail()which will automatically throw a ModelNotFoundExceptionwhen nothing is found:

first()null在未找到记录时返回,因此您的支票可以找到。但是,作为替代,您也可以使用firstOrFail()which 将ModelNotFoundException在未找到任何内容时自动抛出:

$UserProduct = Product::where('seller_id', '=', $userId)->firstOrFail();

(The same is true for find()and findOrFail())

find()和也是如此findOrFail()

Check if query got executed

检查查询是否被执行

Unfortunately with createit's not that easy. Here's the source:

不幸的是,create这并不容易。这是来源:

public static function create(array $attributes)
{
    $model = new static($attributes);

    $model->save();

    return $model;
}

As you can see it will create a new instance of the model with the $attributesand then call save(). Now if save()where to return true you wouldn't know because you'd get a model instance anyways. What you could do for example is check for the models id (since that's only available after the record is saved and the newly created id is returned)

如您所见,它将使用 来创建模型的新实例,$attributes然后调用save(). 现在,如果save()在哪里返回 true,您将不知道,因为无论如何您都会得到一个模型实例。例如,您可以做的是检查模型 ID(因为只有在保存记录并返回新创建的 ID 后才可用)

if(!$newUser->id){
    App::abort(500, 'Some Error');
}

回答by Simon

You can also check the publicattribute $existson your model.

您还可以检查模型上的public属性$exists

if ($myModel->exists) {
    // Model exists in the database
}

回答by Asem Khatib

I would do such move to when I use Model::createmethod :

当我使用Model::create方法时,我会这样做:

$activity = Activity::create($data);

if ($activity->exists) {
   // success
} else {
   // failure 
}

As for the Save method it's easier because $model->save()returns Bool:

至于 Save 方法,它更容易,因为$model->save()返回Bool

$category = new Category();
$category->category_name = $request->category_name;
$is_saved = $category->save();

if ($is_saved) {
    // success
} else {
    // failure 
}

回答by Shanka SMS

/**
 * Store a newly created country in storage.
 *
 * @url /country
 * @method POST
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function store(Request $request)
{
  # Filer & only get specific parameters.
  $request = $request->only('code', 'name', 'status');

  # Assign login user(Auth Control).
  $request['created_by'] = Auth::user()->id;

  # Insert data into `countries` table.
  $country = Country::create($request);

  if(!$country)
    throw new Exception('Error in saving data.');
}