Laravel 6.9 belongtomany关系返回一个集合

Laravel 6.9 belongtomany关系返回一个集合,laravel,relationship,laravel-6,Laravel,Relationship,Laravel 6,我有很多对很多的关系。我有三张桌子: posts posts_tag tags 表“posts”具有标准字段 表“posts_tag”的结构: 表“标记”的结构: 该关系在模型中定义: class Tag extends Model { public function posts() { return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id'); }

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

posts
posts_tag
tags
表“posts”具有标准字段

表“posts_tag”的结构:

表“标记”的结构:

该关系在模型中定义:

 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 [▶]
}


我将感谢任何帮助我的朋友!如果你对我的英语感到抱歉,我正在学习中

在标记模式中

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');
    }
}
在您的帖子中

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);
}

我很抱歉没有写得这么好,就像你写的那样,这是真的!
$id
的值是多少?数据透视表是
posts\u-tag
post\u-tag
?这将是我过滤的id!数据透视表是“posts_tag”!您将哪个
$id
发送到
getPostsByTag
?我是指值。我有路由:
route::get('/tag/{id?}','PostController@getPostsByTag')->name('blog.getPostsByTag')
App\Models\Post{#573▼   #可填充:数组:28[▶]   #连接:“mysql”#表:“posts”#主键:“id”#关系:数组:1[▼     “tags”=>Illumb\Database\Eloquent\Collection{#577▼       #项目:数组:1[▶]     }   ] }-我仍然得到一个数组谢谢你这个好人!问题就在这里:
类Post扩展了模型{public function tags(){return$this->belongomany(Tag::class,'Post_Tag','Tag_id','Post_id');}
它是'return$this->belongomany(Tag::class,'Post_Tag,'Post_id','Tag id'))`是的,要获得某个标记的所有贴子,您需要它如下:
类标记扩展模型{public function posts(){return$this->belongstomy(Post::class,'Post_tag','tag_id','Post_id');}
-'tag id',Post_id'也正好相反——