簡體   English   中英

為文章添加多個類別

[英]Add multiple categories for articles

我需要為一篇新文章添加幾個類別。 我會按順序寫下我所做的一切:

類別遷移

public function up()
    {
        Schema::create('blog_categories', function (Blueprint $table) {
            $table->BigIncrements('id');
            $table->string('title', 128);
            $table->timestamps();
        });
    }

物品遷移

public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->BigIncrements('id');
            $table->string('title', 128);
            $table->string('slug', 64);
            $table->string('subtitle', 256)->nullable();
            $table->timestamps();
        });
    }

創建另一個遷移article_blog_category_table

public function up()
    {
        Schema::create('article_blog_category', function (Blueprint $table) {
            $table->unsignedBigInteger('blog_category_id')->nullable();
            $table->foreign('blog_category_id')
                ->references('id')->on('blog_categories')->onDelete('set null');
            $table->unsignedBigInteger('article_id')->nullable();
            $table->foreign('article_id')
                ->references('id')->on('articles')->onDelete('cascade');
        });
    }

在模型中做belongsToMany

文章 model

public function blog_categories()
    {
        return $this->belongsToMany('App\Models\BlogCategory');
    }

類別 model

public function articles()
    {
        return $this->belongsToMany('App\Models\Article');
    }
}

接下來我在controller中寫了加文章的function(我覺得加分類的function就不用寫了,那里都清楚)

文章 controller

public static function saveArticle(Request $request) {
        $validator = Validator::make($request->all(), [
            'blog_category_id' => 'required|numeric',
            'title' => 'required|max:128',
            'slug' => 'required|unique:articles|max:64',
            'subtitle' => 'max:256',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => $validator->errors()->first()
            ], 422);
        }

        $article = new Article();

        $blog_category = BlogCategory::where('id', $request->blog_category_id)->first();

        if(!$blog_category){
            return response()->json([
                'message' => 'Blog category not found'
                ], 404);
        }

        $article->blog_category_id = $request->blog_category_id;
        $article->title = $request->title;
        $article->slug = $request->slug;
        $article->subtitle = $request->subtitle;

        $article->save();

        return Article::where('slug', $article->slug)->first();
    }

我在function有方法添加一個類。 怎么在這里添加,這樣你就可以添加幾個類別的問題,我想不通。 你需要像$article->blog_categories()->attach($request->blog_category_id); 但如何正確應用呢?

您的命名約定使您的任務復雜化。

重命名類別遷移中的表:

Schema::create('categories', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->timestamps();
});

同樣為了簡單起見,重命名聯合(數據透視)表

Schema::create('article_category', function (Blueprint $table) {
    // You don't need a table id here
    $table->foreignId('category_id')->index();
    $table->foreignId('article_id')->index();
    $table->unique(['article_id', 'category_id']);
    // You also don't need timestamps
});

在模型中定義關系:

// Article model
public function categories()
{
    return $this->belongsToMany(\App\Models\Category::class);
}

// Category model
public function articles()
{
    return $this->belongsToMany(\App\Models\Article::class);
}

文章 controller

public function store() // No need to make the function static
{
    $data = validator(request()->all(), [
        // To save many categories, send them as an array   
        'categories' => 'array',
        'categories.*' => [\Illuminate\Validation\Rule::exists('categories', 'id')], // Checks if category id is in the db
        'title' => 'required|max:128',
        'slug' => 'required|unique:articles|max:64',
        'subtitle' => 'string',
    ])->validate();

    $article = Article::create(
        \Illuminate\Support\Arr::except($data, 'categories');
    );

    // Save categories
    $article->categories()->attach($data['categories']);

    return $article;
}

根據文檔多對多關系附加/分離

//You can pass an array of id's categories in attach method:
$article->blog_categories()->attach($categories_ids_array);

/* 
*if you want to pass more columns value you can pass an associative array of 
*column names with their values e.g attach($categories ids array, an array of 
*more columns with their values)
*/

$article->blog_categories()->attach($categories_ids_array, ['column_name' => 
$column_values]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM