将两个表连接到laravel中

将两个表连接到laravel中,laravel,Laravel,我有两张像下面这样的桌子 Product TABLE id name count 1 book 3 2 shoes 4 3 pen 3 当我像一样查询时,我想要得到结果。。。其中product.id=1 { "id" : 1, "name" : "book", "count" : 3, "categories" : [ 4, 5 ], } 以下代码显示了模型及其关系 模型中的产品 class Product extends Model

我有两张像下面这样的桌子

Product TABLE

id name count
1  book 3
2  shoes 4
3  pen 3
当我像
一样查询时,我想要得到结果。。。其中product.id=1

{
  "id" : 1,
  "name" : "book",
  "count" : 3,
  "categories" : [
      4,
      5
    ],
}
以下代码显示了模型及其关系

模型中的产品

class Product extends Model
{
    protected $fillable = [
        'name',
        'count',
    ];

    public function categories()
    {
        return $this->hasMany(Category::class);
    }
}
控制器

 ...
 $product = Product::with('categories')->get();
 ...

但结果是这样的

{
  "id" : 1,
  "name" : "book",
  "count" : 3,
  "categories" : [
      {
         "category_id": 4
      },
      {
         "category_id": 5
      }
    ],
}

我想我应该使用两个表之间的关系。

试试类似的方法

$product = Product::with((array('categories'=>function($query){
    $query->pluck('category_id');
}))->get();
另一种选择

Product::with('categories:id,category_id')->get()

您可以这样使用

$products = Product::with('categories')->get();
$products->transform(function ($item) {
    $item->categories = $item->categories->pluck('category_id')->all();
});

所以你只希望类别是一个ID数组,而不是一个对象数组?是的,对。我只想得到类别ID数组的结果。
$products = Product::with('categories')->get();
$products->transform(function ($item) {
    $item->categories = $item->categories->pluck('category_id')->all();
});