Kenny Hietbrink
Kenny Hietbrink

Reputation: 684

Multiple attributes in updateOrCreate array (Eloquent)

I'm trying to create a new row if there isn't one yet with the following condition:

['employee_id' => $id, 'competence_id' => $getCompetenceKey]

or if it exists already, I update it and set ['value' => $getCompetenceValue]

So I did this:

foreach($request->input('competence') as $getCompetenceKey => $getCompetenceValue) {
    EmployeeCompetence::updateOrCreate(
     ['employee_id' => $id,'competence_id' => $getCompetenceKey],
     ['value' => $getCompetenceValue]
    );
}

But it doesn't seem to work properly:

https://i.sstatic.net/8ndQt.png

I could do it like this though:

foreach ($request->input('competence') as $getCompetenceKey => $getCompetenceValue) {
    $e = EmployeeCompetence::where('employee_id', $id)->where('competence_id', $getCompetenceKey);
    if ($e->count() > 0) {
        $e->update(['value' => $getCompetenceValue]);
    } else {
            EmployeeCompetence::create(['employee_id' => $id,
                                      'competence_id' => $getCompetenceKey, 
                                              'value' => $getCompetenceValue]);
    }
}

But I really want to know why the updateOrCreate() function didn't work for me.

Thanks,

Kenny

Upvotes: 1

Views: 5345

Answers (3)

rahul singh
rahul singh

Reputation: 449

I also faced issue with updateOrCreate method .

$user = user::updateOrCreate(
    ['email' =>  'xxx'],
    [
        'location' => 'yyy' ,
    ],
);

first I don't need to pass 'email' in 2nd element of argument. we need to create a fillable variable in model class with fields which we want to update .

protected $fillable = ['email' ,'location' ,'column1' ,'colun2'];

this worked for me so thought to post here.thanks.

Upvotes: 0

Hiren Makwana
Hiren Makwana

Reputation: 2156

I'm not sure this will work or not but as per my understanding.

updateOrCreate takes $primaryKey field as a query.

I'm not sure, may be this will solve your problem. Add below line in your model file and then try

protected $primaryKey = ['employee_id', 'competence_id'];

Upvotes: 0

MODEV
MODEV

Reputation: 89

The first column is for update, but it should be also passed in the create function.

Example:

EmployeeCompetence::updateOrCreate(
    [
      'employee_id'   => $id, 
      'competence_id' => $getCompetenceKey
    ],
    [
      'value'         => $getCompetenceValue,
      'employee_id'   => $id, 
      'competence_id' => $getCompetenceKey
    ]
);

Upvotes: 5

Related Questions