source

라벨 모델이 저장되었는지 쿼리가 실행되었는지 확인합니다.

ittop 2023. 8. 5. 11:00
반응형

라벨 모델이 저장되었는지 쿼리가 실행되었는지 확인합니다.

저는 많은 사람들이 이 방법을 사용하여 라벨 모델이 저장되었는지 확인하는 것을 보았습니다.그래서 지금 저는 그것이 안전한 방법인지 궁금합니다.

그리고 아래의 쿼리가 이렇게 실행되었는지 확인할 수 있습니다.

모델 저장 여부 확인

예:

$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);

위의 방법이 내 모델이 저장될 때마다 안전하게 확인할 수 있는 방법입니까?

쿼리가 결과를 반환했는지 확인합니다.

예:

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

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

위에서 제품을 찾을 수 없으면 오류가 반환됩니까?

쿼리가 실행되었는지 확인합니다.

예:

$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);

위에서 사용자가 생성되었는지 확인합니까?

모델 저장 여부 확인

save()저장되었거나 저장되지 않은 부울을 반환합니다.따라서 다음 중 하나를 수행할 수 있습니다.

$saved = $myModel->save();

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

또는 다음과 같은 경우에 직접 저장합니다.

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

전화하는 것은 말이 안 된다는 것을 참고하세요.save()당신의 예처럼 두 번 연속으로.그리고 모델을 저장하지 못하게 하는 많은 오류나 문제는 어쨌든 예외가 될 것입니다.

쿼리가 결과를 반환했는지 확인합니다.

first()돌아올 것입니다null레코드를 찾을 수 없는 경우 체크 작업이 검색됩니다.그러나 대안으로 당신은 또한 사용할 수 있습니다.firstOrFail()자동적으로 그것을 던질 것입니다.ModelNotFoundException아무것도 발견되지 않을 때:

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

(이 경우에도 마찬가지입니다.find()그리고.findOrFail())

쿼리가 실행되었는지 확인합니다.

유감스럽게도create그렇게 쉽지 않아요.출처는 다음과 같습니다.

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

    $model->save();

    return $model;
}

보시는 바와 같이 모델의 새 인스턴스가 생성됩니다.$attributes그리고 나서 전화합니다.save()이제 만약에save()모델 인스턴스를 얻을 수 있기 때문에 알 수 없는 진정한 의미로 반환해야 합니다.예를 들어 모델 ID를 확인할 수 있습니다(기록이 저장되고 새로 생성된 ID가 반환된 후에만 사용할 수 있기 때문).

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

또한 다음을 확인할 수 있습니다.public기여하다$exists당신의 모델에.

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

저는 사용할 때 그런 이동을 할 것입니다.Model::create방법:

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

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

저장 방법은 다음과 같은 이유로 더 쉽습니다.$model->save()돌아온다Bool:

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

if ($is_saved) {
    // success
} else {
    // failure 
}
/**
 * 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.');
}

언급URL : https://stackoverflow.com/questions/27877948/check-if-laravel-model-got-saved-or-query-got-executed

반응형