0

我创建一个这样的表:

帖子

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

我可以得到所有的帖子。

每个相关帖子custom_value都可以返回吗?category_post

4

2 回答 2

0

使用withPivot函数

class Category extends Model
{

  public function posts()
  {
   return $this->belongsToMany(Post::class)->withPivot('custom_value');
  }
}
于 2018-02-26T19:11:25.673 回答
0

你可以使用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');
}
于 2018-02-26T19:09:21.553 回答