1

I have two models:

  • Brands
  • Mods

I can display all brands via belongsTo function. Problem is when I try to save same brand two times, I get error duplicated entry.

This belongsTo is causing duplicated entry error when saving to DB two same brands.

Mods.php

public $belongsTo = [  
  'brand' => [\Slasher\Farming\Models\Brands::class, 'key' => 'id'],    
  ];

This belongsToMany works, and save's data to DB, but is generating checkbox field (I only want to select one brand at one mod enty). I'm using pivot table for this relation.

Mods.php

public $belongsToMany =[  
    'brand' =>[  
        'Slasher\Farming\Models\Brands',  
        'table' => 'slasher_farming_mods_brands',  
        'order' => 'brand_name'  
    ],  
];

BelongsTo example: (Brands are visible and I can save them. But problem is when saving same brand for more than two times). enter image description here

Error I get when saving with belongsTo.

enter image description here

I tried also creating inverse relationships on Brands model with (belongsTo and belongsToMany), but still getting this error.

What type of relation should I make, to save Brands as dropdown list and to fix this duplicate error?

Slasher
  • 568
  • 7
  • 29
  • 1
    means you want a pivot table or just experimenting on it. and you want only a single dropdown to select brand only – Hardik Satasiya Mar 08 '21 at 13:24
  • I managed to find the problem. My mods table didn't have brand_id so I changed brand column to brand_id. And I have to remove key parameter from $belongsTo – Slasher Mar 12 '21 at 07:31
  • 'brand' => ['Slasher\Farming\Models\Brands'] this works now. – Slasher Mar 12 '21 at 07:31
  • 1
    actually, I just suggested it was not answer, you can post your correct code and mark it as an answer so it can be useful to others :) – Hardik Satasiya Mar 12 '21 at 12:29

3 Answers3

0

If you're using a pivot table for your relation, then you should use $belongsToMany. Pivot table is only used for many-to-many relations.

  • I tried to use pivot table only for testing purposes. I need belongsTo relation because I want to select only one brand at one mod. – Slasher Mar 06 '21 at 14:41
0

I fixed this problem with changing column in the mods name brand to brand_id and also changing belongsTo relation. I just removed key, and it works like a charm. No need for pivot table here.

Mods.php

public $belongsTo = [
    'brand' => ['Slasher\Farming\Models\Brands']
];
Slasher
  • 568
  • 7
  • 29
0

"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'PRIMARY' (SQL: update liam_blog_blogs set id = 3, liam_blog_blogs.updated_at = 2022-07-26 09:30:09 where id = 2)"