我需要对一个模型使用多对多关系。我有一个文章模型,我想创建一个函数,以便其他文章(通常推荐)可以附加到一篇文章中。
这就是函数,它应该可以正常工作。
$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');
}
数据库
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)
最佳答案
你想要做什么应该相当简单,它就像一个以下系统,其中每个用户与许多用户(相同的模型)相关,但也与同一个表相关!
您在这里尝试创建另一个我认为不必要的表,您只需要两个表
文章
和推荐
推荐表将充当文章的数据透视表,从而与同一个表创建多对多关系。
文章.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);
关于php - 同一模型中的多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69527232/