laraveloctobercmsoctobercms-pluginsoctobercms-backend

OctoberCMS belongsTo relationship saving problem


I have two models:

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?


Solution

  • 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']
    ];