[php] Laravel Eloquent 생성 및 업데이트

새 레코드를 삽입하거나 존재하는 경우 업데이트하는 속기는 무엇입니까?

<?php

$shopOwner = ShopMeta::where('shopId', '=', $theID)
    ->where('metadataKey', '=', 2001)->first();

if ($shopOwner == null) {
    // Insert new record into database
} else {
    // Update the existing record
}



답변

“lu cip”가 말한 내용의 전체 예는 다음과 같습니다.

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save();

아래는 최신 버전의 Laravel에있는 문서의 업데이트 된 링크입니다.

여기 문서 : 업데이트 된 링크


답변

업데이트 : 2014 년 8 월 27 일-[ updateOrCreate내장 코어 …]

사람들이 여전히이 문제를 겪고있는 경우를 대비해서 …이 글을 쓰고 몇 주 후에 이것이 실제로 Laravel의 Eloquent의 핵심의 일부라는 것을 알게되었습니다.

Eloquent의 동등한 방법으로 파기. 당신은 여기에서 볼 수 있습니다 :

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L553

: 570 및 : 553

    /**
     * Create or update a record matching the attributes, and fill it with values.
     *
     * @param  array  $attributes
     * @param  array  $values
     * @return static
     */
    public static function updateOrCreate(array $attributes, array $values = array())
    {
        $instance = static::firstOrNew($attributes);

        $instance->fill($values)->save();

        return $instance;
    }

아래의 오래된 답변


다음과 같은 방법으로 L4 기능이 내장되어 있는지 궁금합니다.

$row = DB::table('table')->where('id', '=', $id)->first();
// Fancy field => data assignments here
$row->save();

몇 주 전에이 방법을 만들었습니다 …

// Within a Model extends Eloquent
public static function createOrUpdate($formatted_array) {
    $row = Model::find($formatted_array['id']);
    if ($row === null) {
        Model::create($formatted_array);
        Session::flash('footer_message', "CREATED");
    } else {
        $row->update($formatted_array);
        Session::flash('footer_message', "EXISITING");
    }
    $affected_row = Model::find($formatted_array['id']);
    return $affected_row;
}

도움이 되길 바랍니다. 누군가 공유 할 것이 있다면 이것에 대한 대안을보고 싶습니다. 아리따움


답변

2020 업데이트

마찬가지로 Laravel> = 5.3 , 누군가는 쉬운 방법으로 그 방법을 여전히 궁금합니다. 다음을 사용하여 가능합니다 updateOrCreate().

예를 들어 질문과 같은 경우 다음과 같은 것을 사용할 수 있습니다.

$matchThese = ['shopId'=>$theID,'metadataKey'=>2001];
ShopMeta::updateOrCreate($matchThese,['shopOwner'=>'New One']);

위의 코드는 ShopMeta로 표시되는 테이블을 확인하며, shop_metas모델 자체에서 달리 정의하지 않는 한 가장 가능성이 높습니다

그리고 그것은 항목을 찾으려고 노력할 것입니다

기둥 shopId = $theID

기둥 metadateKey = 2001

찾은 경우 shopOwner찾은 행의 열 을로 업데이트 합니다 New One.

하나 이상의 일치하는 행을 찾으면 가장 낮은 기본 행을 의미하는 첫 번째 행을 업데이트합니다 id.

전혀 찾지 못하면 다음과 같이 새 행을 삽입합니다.

shopId = $theID, metadateKey = 2001shopOwner = New One


유의 사항 모델을 점검 $fillable하고 삽입 또는 갱신 할 컬럼 이름을 정의하고 나머지 컬럼에 기본값 또는 id컬럼 자동 증가 값이 있는지 확인하십시오 .

그렇지 않으면 위의 예제를 실행할 때 오류가 발생합니다.

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field '...' doesn't have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))'

새 행을 삽입하는 동안 값이 필요한 일부 필드가 있으므로 정의되지 않았 $fillable거나 기본값 이 없으므로 불가능 합니다.

자세한 내용은 Laravel 설명서 ( https://laravel.com/docs/5.3/eloquent) 를 참조하십시오.

거기에서 하나의 예는 다음과 같습니다

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

거의 모든 것을 지 웁니다.

쿼리 빌더 업데이트

누군가 라 라벨에서 Query Builder를 사용할 수 있는지 물었다. 다음 은 Laravel 문서의 Query Builder에 대한 참조입니다.

Query Builder는 Eloquent와 정확히 동일하게 작동하므로 Eloquent에 해당되는 것은 Query Builder에도 적용됩니다. 따라서이 특정 경우 쿼리 작성기와 동일한 기능을 다음과 같이 사용하십시오.

$matchThese = array('shopId'=>$theID,'metadataKey'=>2001);
DB::table('shop_metas')::updateOrCreate($matchThese,['shopOwner'=>'New One']);

물론 DB 파사드를 추가하는 것을 잊지 마십시오.

use Illuminate\Support\Facades\DB;

또는

use DB;

나는 그것이 도움이되기를 바랍니다


답변

기능 저장 :

$shopOwner->save()

벌써 네가 원하는 걸 해

라 라벨 코드 :

    // If the model already exists in the database we can just update our record
    // that is already in this database using the current IDs in this "where"
    // clause to only update this model. Otherwise, we'll just insert them.
    if ($this->exists)
    {
        $saved = $this->performUpdate($query);
    }

    // If the model is brand new, we'll insert it into our database and set the
    // ID attribute on the model to the value of the newly inserted row's ID
    // which is typically an auto-increment value managed by the database.
    else
    {
        $saved = $this->performInsert($query);
    }


답변

firstOrNew존재하지 않는 경우 레코드를 작성하고 이미 존재하는 경우 행을 업데이트합니다. 당신은 또한 updateOrCreate여기 전체 예제를 사용할 수 있습니다

$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
); 

오클랜드 발 샌디에이고 행 항공편이 있다면, 가격을 $ 99로 설정하십시오. 존재하지 않는 경우 새 행을 작성하십시오.

여기에 참조 문서 : ( https://laravel.com/docs/5.5/eloquent )


답변

를 사용하여 동일한 기능이 필요한 경우 DBLaravel에서 >= 5.5다음을 사용할 수 있습니다.

DB::table('table_name')->updateOrInsert($attributes, $values);

또는 속기 버전 $attributes$values동일합니다 :

DB::table('table_name')->updateOrInsert($values);


답변

$shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));

그런 다음 변경하고 저장하십시오. firstOrNew는 삽입이 없으면 firstOrCreate를 수행하지 않습니다.