Laravel Nova多对多关系表

问题描述

我有2个模型-商店和产品具有多对多关系。我如何显示其类似表格,其中列是商店,行是产品。单元格中必须有用于将产品附着或分离到商店的复选框。

解决方法

多对多时,您是说belongsToMany口才好吗?如果是这种情况,那么Nova documentation很清楚。

以下是直接来自文档(#belongstomany)的示例:

将以下内容添加到Model Nova资源(在本示例中为User):

use Laravel\Nova\Fields\BelongsToMany;

BelongsToMany::make('Roles');

此外,如果您还有其他枢纽字段:

BelongsToMany::make('Roles')
    ->fields(function () {
        return [
            Text::make('Notes'),];
    });

与关系的倒数(Roles资源):

BelongsToMany::make('Users')
    ->fields(function () {
        return [
            Text::make('Notes'),];
    });

注意:额外字段是您在belongsToMany关系中的口才关系中定义的字段:

    /**
     * The roles which the user belongs to.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class,'user_role')
                    ->withPivot(['notes']) // Add extra fields to the 'pivot' object
                    ->withTimestamps(); // Enable timestamps (created_at and updated_at fields)
    }

然后可以从枢纽对象访问哪个

$user = User::findOrFail(1);
foreach($user->roles as $role){
    echo $role->pivot->notes;
}