首页 > 解决方案 > Laravel 6.9 belongsToMany 关系返回一个集合

问题描述

我有多对多的关系。我有三张桌子:

posts
posts_tag
tags

表“帖子”具有标准字段。

表“posts_tag”的结构:

Schema::create('post_tag', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts');

    $table->bigInteger('tag_id')->unsigned();
    $table->foreign('tag_id')->references('id')->on('tags');
});

表“标签”的结构:

Schema::create('tags', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});

该关系在模型中定义:

 class Tag extends Model
{

        public function posts()
    {
        return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
    }
}

我称之为方法$tag->posts

public function getPostsByTag($id)
{
    $tag = Tag::find($id);

    dd($tag->posts);

}

我只有一个数组:

Illuminate\Database\Eloquent\Collection {#571 ▼
  #items: array:1 [▶]
}

截图数据库

如果有帮助的朋友,我将不胜感激!如果你对我的英语感到抱歉,我正在学习中!

标签: laravelrelationshiplaravel-6

解决方案


在您的标签模式中

class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
    }
}

在您的帖子模式中

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class,'post_tag', 'tag_id', 'post_id');
    }
}

在您的控制器中

public function getPostsByTag($id)
{
    $tag = Post::with('tags')->find($id);
    dd($tag);
}

推荐阅读