Creating and Update Laravel Eloquent

后端 未结 13 1455
广开言路
广开言路 2020-11-27 11:59

What\'s the shorthand for inserting a new record or updating if it exists?



        
13条回答
  •  眼角桃花
    2020-11-27 12:53

    2020 Update

    As in Laravel >= 5.3, if someone is still curious how to do so in easy way. Its possible by using : updateOrCreate().

    For example for asked question you can use something like:

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

    Above code will check the table represented by ShopMeta, which will be most likely shop_metas unless not defined otherwise in model itself

    and it will try to find entry with

    column shopId = $theID

    and

    column metadateKey = 2001

    and if it finds then it will update column shopOwner of found row to New One.

    If it finds more than one matching rows then it will update the very first row that means which has lowest primary id.

    If not found at all then it will insert a new row with :

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

    Notice Check your model for $fillable and make sue that you have every column name defined there which you want to insert or update and rest columns have either default value or its id column auto incremented one.

    Otherwise it will throw error when executing above example:

    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))'
    

    As there would be some field which will need value while inserting new row and it will not be possible as either its not defined in $fillable or it doesnt have default value.

    For more reference please see Laravel Documentation at : https://laravel.com/docs/5.3/eloquent

    One example from there is:

    // 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]
    );
    

    which pretty much clears everything.

    Query Builder Update

    Someone has asked if it is possible using Query Builder in Laravel. Here is reference for Query Builder from Laravel docs.

    Query Builder works exactly the same as Eloquent so anything which is true for Eloquent is true for Query Builder as well. So for this specific case, just use the same function with your query builder like so:

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

    Of course, don't forget to add DB facade:

    use Illuminate\Support\Facades\DB;
    

    OR

    use DB;
    

    I hope it helps

提交回复
热议问题