First Or Create

前端 未结 4 1585
耶瑟儿~
耶瑟儿~ 2020-12-02 15:18

I know using:

User::firstOrCreate(array(\'name\' => $input[\'name\'], \'email\' => $input[\'email\'], \'password\' => $input[\'password\']));


        
相关标签:
4条回答
  • 2020-12-02 15:33

    Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

    $user = User::firstOrCreate([
        'email' => 'dummy@domain.com'
    ], [
        'firstName' => 'Taylor',
        'lastName' => 'Otwell'
    ]);
    
    0 讨论(0)
  • 2020-12-02 15:35

    firstOrCreate() checks for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created.

    If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.

    The difference between firstOrCreate() and firstOrNew():

    • firstOrCreate() will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.
    • firstOrNew() will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.

    Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name or some mandatory field), you should use firstOrNew(). If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate().

    0 讨论(0)
  • 2020-12-02 15:39

    firstOrCreate() checks for all the arguments to be present before it finds a match.

    If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like

    $user = User::firstOrCreate([
        'email' => 'abcd@gmail.com'
    ], [
        'firstName' => 'abcd',
        'lastName' => 'efgh',
        'veristyName'=>'xyz',
    ]);
    
    

    Then it check only the email

    0 讨论(0)
  • 2020-12-02 15:48

    An update:

    As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.

    The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:

    See documentation

    0 讨论(0)
提交回复
热议问题