Laravel 6.9 includesToMany Relationships返回一个集合

桑德

我有很多对很多关系。我有三个表:

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

屏幕截图数据库

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

维卡斯(Vikas Katariya)

在您的代码模式中

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Laravel includesToMany不返回相关数据

laravel 5 includesToMany使用主键作为表

Laravel includesToMany排除数据透视表

laravel includesToMany自引用附加关系

BookshelfJS includesToMany不返回重复项

构建一个始终显示为6或9的幂的计算器

在sqlite3中声明一个十进制(9,6)字段

Plucked Laravel Eloquent Collection Diff 总是返回一个空集合

Laravel集合循环到另一个集合

如何声明一个变量以用于Laravel 6及更高版本的laravel中的所有函数?

在 laravel 9 中的特定用户的另一个模型的下拉列表中显示数据

Xcode 6与iOS 9?

使用Laravel中的GuzzleClient从另一个应用程序返回原始数据类型(集合)

laravel 6用户ID返回null

Laravel 6-HasMorph关系返回空

如何在 Laravel 6 中返回图像?

如何根据另一个外键显示的外键显示表格/ Laravel 6

如何表单提交输入数据以显示在 Laravel 6 的另一个视图中

在 Laravel 6 中注册另一个表关系

Laravel将一个模型实例转换为集合

使用数组循环遍历一个集合-Laravel

集合上的Laravel块将第一个元素作为数组返回,第二个作为对象返回

Laravel 9 访问器不返回值

我通过在 laravel 集合上运行 filter 方法得到的过滤结果返回一个带有不需要的索引的新集合

laravel 9.x 将控制器变量传递给另一个文件

Laravel 9 枚举条件 if

Laravel 5.5。-从两个集合创建一个集合

Laravel 9 路由组有两个条件

Laravel不返回第一个返回