使用默认类别CategoriesToMany创建新帖子

时间:2019-07-04 13:57:42

标签: laravel laravel-nova

我有一个Post / Category manyToMany关系,并希望能够将一个名为“未分类”的默认类别附加到所创建的每个新帖子中。我怎样才能做到这一点? BelongsToMany方法仅在“详细信息”页面上起作用,而不在“创建”页面上起作用。

BelongsToMany::make(__('Categories'), 'categories', Category::class),

3 个答案:

答案 0 :(得分:2)

您还可以在数据库字段中设置默认值,以便您可以省略传递类别,并且默认为未归类,例如,如果您使用的是MySQL,则可以通过创建迁移来做到这一点< / p>

$table->text('category')->default(0);

答案 1 :(得分:0)

因为在Post Nova模型中创建的模式下未显示BelongsToMany。因此,我们必须通过将以下代码添加到您的字段中来进行自定义选择:

public function fields(Request $request)
{
    if($request->editMode=="create"){
        $categories = \App\Category::get(['id','name']);
        $options = [];
        foreach($categories as $value){
            $options[$value->id] = $value->name;
        }
        return [
            ID::make()->sortable(),
            Text::make('Title'),
            Text::make('Summary'),
            Textarea::make('Content'),
            Select::make('Categories', 'category_id')
            ->options($options)
            ->displayUsingLabels()
            ->withMeta(['value' => 1]) // 1 = id of Uncategorised in categories table
        ];
    }
    return [
        ID::make()->sortable(),
        Text::make('Title'),
        Text::make('Summary'),
        Textarea::make('Content'),
        BelongsToMany::make('Categories','categories')->display('name'),
    ];
}

在帖子和类别模型中都不要忘记关系功能:

class Post extends Model
{
    public function categories(){
        return $this->belongsToMany(Category::class, 'category_post', 'post_id', 'category_id');
    }
}

并且:

class Category extends Model
{
    public function posts(){
        return $this->belongsToMany(Post::class,'category_post', 'category_id', 'post_id');
    }
}

然后,自定义函数在POST资源页面创建模式下处理数据,位于nova \ src \ Http \ Controllers \ ResourceStoreController.php,将函数句柄更改为此:

    public function handle(CreateResourceRequest $request)
    {
        $resource = $request->resource();

        $resource::authorizeToCreate($request);

        $resource::validateForCreation($request);

        $model = DB::transaction(function () use ($request, $resource) {
            [$model, $callbacks] = $resource::fill(
                $request, $resource::newModel()
            );

            if ($request->viaRelationship()) {
                $request->findParentModelOrFail()
                        ->{$request->viaRelationship}()
                        ->save($model);
            } else {
                $model->save();
                // your code to save to pivot category_post here
                if(isset($request->category_id)&&($resource=='App\Nova\Post')){
                    $category_id = $request->category_id;
                    $post_id = $model->id;
                    \App\Post::find($post_id)->categories()->attach($category_id);
                }
            }

            ActionEvent::forResourceCreate($request->user(), $model)->save();

            collect($callbacks)->each->__invoke();

            return $model;
        });

        return response()->json([
            'id' => $model->getKey(),
            'resource' => $model->attributesToArray(),
            'redirect' => $resource::redirectAfterCreate($request, $request->newResourceWith($model)),
        ], 201);
    }
}

在我的计算机上,所有程序运行良好。我有一个有趣的问题!希望对您最好,问我是否需要!

答案 2 :(得分:0)

我最终要做的是将数据保存在boot()中的Post Model上。

public static function boot()
{
    parent::boot();

    static::created(function (Post $post) {

        $post->categories()->attach([1]);

    });
}