php - Laravel 多对多不工作

标签 php mysql laravel

我有一个基本的多对多关系:

Posts
Tags

我有一个名为 post_tag 的数据透视表。

我正在尝试在我的 View 文件中返回所有给定的帖子标签:

@foreach($posts as $post)

    {{ dd($post->tags)  }}

@endforeach

我收到以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tags.post_id' in 'where clause' (SQL: select * from tags where tags.post_id = 1 and tags.post_id is not null) (View: C:\wamp\www\laravel\resources\views\posts\index.blade.php)

这是我的模型:

class Post extends Model
{
   ....

    public function tags() {
        return $this->hasMany(\App\Models\Tag::class);
    }

}


class Tag extends Model
{
  ....

    public function posts() {
        return $this->belongsToMany(\App\Models\Post::class);
    }

}

关于这里发生的事情有什么想法吗?我在数据透视表中有数据,但关系似乎无法正常工作。

最佳答案

你应该对这两个关系使用 belongsToMany

class Post extends Model
{
   ....

    public function tags() {
        return $this->belongsToMany(\App\Models\Tag::class);
    }

}

关于php - Laravel 多对多不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46074660/

相关文章:

mysql - 如何使用 concat 和 UPPER 在 sql 查询中搜索多个列

mysql - 我如何从 sql 中的 select 语句返回字符串字段

php - Laravel Scout - 搜索垃圾记录并保持软删除模型更新

php - Laravel 5: Auth::guard($this->getGuard())->login($user); 之间的区别和 auth()->login($user);

php - 在中间件之后执行服务提供者

php - Mysql 在没有 mysql_connect 的情况下通过 PHP 使用临时表

php - 如何在一行中显示SQL查询结果?

c# - 从 C# 应用程序内部存储空整数值

php - mPDF 文档自动高度(POS 打印机)

php - opencart 3如何在 Twig 页面中自定义变量