2

i have two table widget and page_widget

PageWidget model:

protected $fillable = [
    'page_id',
    'widget_codes',
    'created_by',
    'updated_by',
    'deleted_by',
    'deleted_at'
];

relation in this model:

public function widgets() {
    return $this->belongsToMany(Widget::class, null, 'page_widget_ids',
        'widget_codes');

}

widget model:

protected $fillable = [
    'name',
    'code',
    'type',
    'page_widget_ids',
    'created_by',
    'deleted_by',
    'deleted_at'
];

on time of store i have to sync widget_code, and i use like this:

$pageWidget->widgets()->sync($input['widget_codes']);

it's doesn't work because in widget model it default primary key considered _id column and i want to give relation with code column

i try $primaryKey = 'code' in widget model but i'cant use this because widget model's other relation use with _id column.

  • Your model schema seems to be wrong. If you are using many to many relation, then there will be a pivot-table holding the `page_id` of page and `code` of widget model. In that case, you don't need to define `page_widget_ids` on any of your relations. – Kalesh Kaladharan May 21 '20 at 11:32
  • Please add the complete schema of page and widget model including `id` fields if it exists. – Kalesh Kaladharan May 21 '20 at 11:35
  • page_id is not primary key of page_widget table it's common column – Denisha Asodariya May 21 '20 at 11:37
  • I have posted an answer. That's the correct way to do a many to many relationship (from the docs). You have to change the table schema and create a pivot table for `sync` to work. – Kalesh Kaladharan May 21 '20 at 15:26

1 Answers1

0

When working with many-to-many relationship you need three tables page_widget, page_widget_widget and widget.

PageWidget model schema should look like this

protected $fillable = [
    'id',
    'created_by',
    'updated_by',
    'deleted_by',
    'deleted_at'
];

Widget model schema should look like

protected $fillable = [
    'name',
    'code', //primary_key
    'type',
    'created_by',
    'deleted_by',
    'deleted_at'
];

And the page_widget_widget table should have an id, page_widget_id and widget_code column.

After that, update your relationship to this

public function widgets() {
    return $this->belongsToMany(Widget::class, 'page_widget_widget', 'page_widget_id', 'widget_code');

}

Your sync function should work now.

Kalesh Kaladharan
  • 1,038
  • 1
  • 8
  • 26
  • Thanks for your response, but i use jenssegers-mongodb so i dont think i need to use third table mongodb manage this in object.i only confuse about primary key,on time of sync i want 'code' column of widget as a primary key. – Denisha Asodariya May 21 '20 at 15:49