如何获得 laravel 多对多关系

How do I get a laravel many to many relationship

我的 laravel 博客项目中的 Post 模型和类别模型之间存在多对多关系。 我正在尝试获取具有特定类别 ID 的帖子,例如

public function categoryPosts($category_id)
    {
        $posts = Post::whereHas('categories' , function($cat) use($category_id){
            $cat->where('id' , $category_id);
        })->get();
    }

而查询到这个控制器的路由是这样的

Route::get('/view/categories/posts/{category_id}' , [CategoryController::class , 'categoryPosts'])->name('category.posts');

我遇到了一个例外

Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `posts` where exists (select * from `categories` inner join `category_post` on `categories`.`id` = `category_post`.`category_id` where `posts`.`id` = `category_post`.`post_id` and `id` in (2)))

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    
    protected $guarded =  [];

    public function categories(){
        return $this->belongsToMany(Category::class);
    }
}

这里是品类模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = ['name'];

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

这是迁移

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->timestamps();
        });
    }
public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title')->unique();
            $table->string('image_path');
            $table->string('slug');
            $table->text('content');
            $table->timestamps();
        });
    }
public function up()
    {
        Schema::create('category_post', function (Blueprint $table) {
            $table->id();
            $table->foreignId('category_id')->constrained();
            $table->foreignId('post_id')->constrained();
            $table->timestamps();
        });
    }

您需要更改 where 条件。

来自

$cat->where('id' , $category_id);

$cat->where('categories.id' , $category_id);

用post和分类关系再做一个table,像这样:

Schema::create('posts_post_categories', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_categories_id')->unsigned();
            $table->foreign('post_categories_id')->references('id')->on('post_categories');
            $table->integer('post_id')->unsigned();
            $table->foreign('post_id')->references('id')->on('posts');
            $table->softDeletes();
        });

模型中 Post

public function category()
    {
        return $this->belongsToMany(PostCategory::class, 'posts_post_categories', 'post_id', 'post_categories_id');
    }

在模型类别中

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

在控制器中获取posts,例如

public function showCategory($url){
    $category = PostCategory::where('url',$url)->first();
    $posts = $category->posts()->paginate(7);
    $recentsPosts = Post::orderBy('created_at','Desc')->take(5)->get();
    $categories = PostCategory::all();
    return view('site.blog.category.index', compact('posts','categories','recentsPosts','category'));
  }

不使用这个

$posts = Post::whereHas('categories' , function($cat) use($category_id){
    $cat->where('id' , $category_id);
})->get();

你可以只使用

$category = Category::with('posts')->where("id", $category_id);
$posts = $catetory->exists() ? $category->first()->posts : [];