在 laravel 中的多对多 eloquent 关系中获取额外数据

get extra data in Many To Many eloquent-relationships in laravel

我创建了一个 table 这样的:

posts

  id title

类别

 id name

category_post

   post_id
   category_id
   custom_value

类别模型中:

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

使用此命令:

$category = Category::find(1);
$posts = $category->posts()->get();

我可以得到所有 posts。

有可能 return custom_value in category_post 每个相关 post?

你可以使用withPivot()方法

return $this->belongsToMany(Post::class)

public function posts()
{
        return $this->belongsToMany(Post::class)->withPivot('column1','column2');
}

public function categories()
{
        return $this->belongsToMany(Category::class)->withPivot('column1','column2');
}

使用withPivot函数

class Category extends Model
{

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