【问题标题】:Laravel Nova Many To Many relationship tableLaravel Nova 多对多关系表
【发布时间】:2020-09-21 08:05:01
【问题描述】:

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

【问题讨论】:

    标签: laravel-nova


    【解决方案1】:

    你说的多对多是指belongsToMany Eloquent 关系吗?如果是这样,那么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 关系中的 Eloquent 关系中定义的字段:

        /**
         * 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 2021-05-20
      • 2019-02-02
      • 2016-12-20
      • 1970-01-01
      • 2018-06-15
      • 2018-01-22
      • 2016-02-26
      • 2016-01-04
      相关资源
      最近更新 更多