【问题标题】:Laravel 6.9 belongsToMany Relationships return one collectionLaravel 6.9 belongsToMany 关系返回一个集合
【发布时间】:2020-06-03 12:27:02
【问题描述】:

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

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

screenshot database

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

【问题讨论】:

  • 我很抱歉没有这样写,所以你写的那样,所以有!
  • $id 的值是多少?并且数据透视表是posts_tagpost_tag?
  • 这将是我过滤的ID!数据透视表是“posts_tag”!
  • 您将哪个$id 发送给getPostsByTag?我的意思是价值。
  • 我有路线:Route::get('/tag/{id?}', 'PostController@getPostsByTag')->name('blog.getPostsByTag');

标签: laravel relationship laravel-6


【解决方案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');
    }
}

在你的控制器中

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

【讨论】:

  • App\Models\Post {#573 ▼ #fillable: array:28 [▶] #connection: "mysql" #table: "posts" #primaryKey: "id" #relations: array:1 [▼ "tags" => Illuminate\Database\Eloquent\Collection {#577 ▼ #items: array:1 [▶] } ] } - 我仍然得到一个数组
  • 谢谢好人!问题出在这里:class Post extends Model { public function tags() { return $this->belongsToMany(Tag::class,'post_tag', 'tag_id', 'post_id'); } } 它是`return $this->belongsToMany(Tag::class,'post_tag', 'post_id', 'tag_id');`
  • 是的,要获取某个标签的所有帖子,您需要它是这样的:class Tag extends Model { public function posts() { return $this->belongsToMany(Post::class,'post_tag', 'tag_id', 'post_id'); } } - 'tag_id', 'post_id' 也相反 -
猜你喜欢
  • 2020-02-02
  • 2014-11-23
  • 1970-01-01
  • 2020-09-09
  • 2018-02-12
  • 2019-08-30
  • 2018-01-31
  • 2020-10-02
  • 2015-02-22
相关资源
最近更新 更多