首页 > 解决方案 > 同一模型中的多对多

问题描述

我需要对一个模型使用多对多关系。我有一个 Article 模型,我想创建一个函数,以便通常推荐的其他文章可以附加到一篇文章。

这是功能,它应该可以正常工作。


$article = Article::where('id', $request->article_id)->first();

$articles_ids = json_decode($request->articles_ids);

$article->articles()->attach($articles_ids);

我有一个关于如何在数据库和模型中正确创建关系表的问题,我是这样做的,但即使迁移也不适合我

模型

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

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

D b

Schema::create('article_article_recommended', function (Blueprint $table) {
            $table->unsignedBigInteger('article_recommended_id')->nullable();
            $table->foreign('article_recommended_id')
                ->references('id')->on('article_recommended')->onDelete('set null');
            $table->unsignedBigInteger('article_id')->nullable();
            $table->foreign('article_id')
                ->references('id')->on('articles')->onDelete('cascade');
        });

迁移错误

SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 
'article_recommended' (SQL: alter table `article_article_recommended` add constraint 
`article_article_recommended_article_recommended_id_foreign` foreign key 
(`article_recommended_id`) references `article_recommended` (`id`) on delete set null)

标签: phplaravel

解决方案


您要做什么应该相当简单,就像一个以下系统,其中每个用户都与许多用户(同一模型)相关,但也与同一张表相关!

你在这里试图创建另一个我认为不必要的表,你只需要两个表

articles&recommendations

并且推荐表将作为文章的数据透视表,其 slef 从而与同一个表创建多对多关系。

文章.php
public function recommendations() {
        return $this->belongsToMany(Article::class , 'recommendations' , 'article_id' , 'recommended_article_id');
    }

create_recommendations_table.php

 Schema::create('recommendations', function (Blueprint $table) {
            $table->primary(['article_id','recommended_article_id']);
            $table->foreignId('article_id');
            $table->foreignId('recommended_article_id');
            $table->timestamps();


            $table->foreign('article_id')->references('id')->on('article')->onDelete('cascade');
            $table->foreign('recommended_article_id')->references('id')->on('articles')->onDelete('cascade');
        });

用法

$article->recommendations()->attach($articles_ids);

推荐阅读