首页 > 解决方案 > 为 laravel nova 上的数据透视表属性创建更新操作 belongsToMany 关系

问题描述

我的模型看起来像下面的Product模型代码:

public class Product extends Model
{
    public function types()
    {
        return $this->belongsToMany(Type::class)
            ->withPivot('published');
    }
}

这里是Types模型:

public class Type extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class)
            ->withPivot('published');
    }
}

在 novaProjectResource我有以下字段:

BelongsToMany::make('Types')
    ->fields(function() {
        return [
            Boolean::make('Published')
        ];
     })->actions(function() { return new Action/UpdateProductTypeActions }),

在 novaTypeResource我有以下字段:

BelongsToMany::make('Projects')
        ->fields(function() {
            return [
                Boolean::make('Published')
            ];
         }),

我想让published 数据透视表中的这个属性可以使用Nova Actions

我已经创建UpdateProductTypeActions了如下代码:

public function handle(ActionFields $fields, Collection $models)
    {
        foreach ($models as $model) {

        }
    }

我的问题如何product_id从这些行动中得到?

标签: laravellaravel-novalaravel-models

解决方案


这将为您提供与与 $model 具有多对多关系的类型具有多对多关系的所有产品,这是您的项目:

 foreach($model->types as $type)
   {
     $products=$type->products->pluck(id);
   }

推荐阅读