1

I'm trying to save changes to a record in one database table, that has a composite key of 2 elements. When i try to use the Model::updateOrCreate or, Model::firstOrCreate methods, i get an error from the database, which tells me the id does not exists. Looks like that laravel, when creating the query, is ignoring the primery keys i've mentioned.

My model:

class CatalogueCatLanguage extends Model
{
  public $incrementing = false;
  protected $table = "CatalogueCatLanguages";
  protected $fillable = ["cataloguecategory_id","language_id","name","description"];
  protected $primaryKey = ["cataloguecategory_id","language_id"];
}

My code inside the controller method:

CatalogoCatLingua::updateOrCreate(
 [
   "cataloguecategory_id"=>$trad["category"],
   "language_id"=>$trad["language"]
 ],[
   "name"=>$trad["langName"],
   "description"=>$trad["langDescription"]
 ]
);

The error i get when i have the "primaryKey" property:

Illegal offset type in isset or empty

The error i get when i have the "primaryKey" property commented:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'

I've already tried several combinations and ways of doing this, however i'm not getting what is causing this error.

Thank you, in advance.

Tiago
  • 23
  • 1
  • 4
  • Strange, I came here looking for answers with the same use case in supporting multiple language. – Philip Borbon Jul 03 '20 at 08:12
  • For anyone stumbled into this from google search, overriding `setKeysForSaveQuery` could resolved this issue as detailed in this post https://laracasts.com/discuss/channels/laravel/illegal-offset-type-while-updating-model. – Philip Borbon Jul 03 '20 at 08:35

1 Answers1

1

Laravel doesn't support composite primary keys (you can try this solution though). You can use string only here:

protected $primaryKey = "cataloguecategory_id";
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • 1
    As @Alexey posted, you can define one of the primary keys in the Model and pass both primary keys in the Controller, as the first of the two parameters of the updateOrCreate method, that receives two arrays. – Fellipe Sanches Apr 14 '20 at 21:33