BelongToMany when primary key is another column of related model

Viewed 129

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.

1 Answers

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.

Related