andrewalkermo's avatar

updateOrCreate through relation needs primary key

I have two tables foo and bar, and bar has a composite unique index:

foo

  • id
  • bar_id

bar

  • id
  • partial_unique_a
  • partial_unique_b
  • partial_unique_c
public function bar(): BelongsTo  
{  
    return $this->belongsTo(Bar::class, 'bar_id');  
}

I'm trying to save bar through a relation with foo, but the resultant query appends bar.id IS NULL.

$foo->bar()->updateOrCreate(  
    [  
        'partial_unique_a' => 'a', 
        'partial_unique_b' => 'b',  
        'partial_unique_b' => 'c,  
    ]  
);

Resulting select query:

select
  *
from
  `bar`
where
  `bar`.`id` is null
  and (
    `partial_unique_a` = 'a'
    and `partial_unique_b` = 'b'
    and `partial_unique_c` = 'c'
  )
limit
  1

This always results in an attempt to create a new one and fails when it already exists. If I try to use Bar::updateOrCreate directly, it works fine.

Is there some misconfiguration that I'm missing here?

0 likes
1 reply

Please or to participate in this conversation.