使用Laravel Backpack中内联创建Many-to-Many关系的方法
在Laravel中使用Backpack for Laravel来处理Many-to-Many关系时,需要使用内联表单和JavaScript来创建新的条目,然后将其添加到中间表中。
以下是示例代码:
class User extends Model
{
protected $fillable = ['name'];
public function roles()
{
return $this->belongsToMany(Role::class)->withTimestamps();
}
}
class Role extends Model
{
protected $fillable = ['name'];
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
}
$this->crud->addField([
'name' => 'roles',
'label' => 'Roles',
'type' => 'checklist',
'entity' => 'roles',
'attribute' => 'name',
'model' => Role::class,
'pivot' => true,
'inline_create' => [
'entity' => 'roles',
'create_button_label' => 'Add new role',
'fields' => [
[
'name' => 'name',
'label' => 'Name',
'type' => 'text',
]
]
],
]);
(function () {
$(document).ready(function () {
var roles = $('#field-roles');
roles.on('change', function () {
var items = $(this).val();
if (items.includes('__inline__')) {
var url = '/admin/roles';
var method = 'POST';
var data = {
name: $('#inline_field-roles-name').val()
};
$.ajax({
url: url,
method: method,
data: data,
success: function (result) {
var option = new Option(result.name, result.id, true, true);
roles.append(option).trigger('change');
$('#inline_form-roles').modal('hide');
}
});
}
});
});
})();
注意:需要将/admin/roles
更