Find or Create with Eloquent

后端 未结 6 1849
我在风中等你
我在风中等你 2020-12-06 04:22

I have recently started working with Laravel and Eloquent, and was wondering about the lack of a find or create option for models. You could always write, for example:

6条回答
  •  情深已故
    2020-12-06 04:49

    In Laravel 5:
    There are two methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew.
    The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the given attributes.
    The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:

    // Retrieve the flight by the attributes, or create it if it doesn't exist...
    $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
    
    // Retrieve the flight by the attributes, or instantiate a new instance...
    $flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
    

提交回复
热议问题