【发布时间】:2019-12-01 23:21:40
【问题描述】:
我有一个关于LARAVEL API 的小问题。如何在同一资源中返回和连接数据透视表的数据?我有 3 个表、库存、产品和库存产品。最后一张表有库存和价格数据(产品的,因为它们因库存而异),我想列出产品并显示价格和库存(来自数据透视表)
我上传了产品控制器、库存和产品模型以及产品资源。顺便说一句,正如我现在所做的那样,价格和股票返回 null。
到目前为止,在我的 ProductController 中:
public function index()
{
return ProductResource::collection(Product::with('inventories')->paginate(25));
}
在我的产品模型中:
class Product extends Model
{
public function inventories()
{
return $this->belongsToMany('App\Inventory','inventory_product')->withPivot('price','stock')->withTimestamps();
}
}
在我的库存模型中:
class Inventory extends Model
{
public function products()
{
return $this->belongsToMany('App\Product','inventory_product')->withPivot('price','stock')->withTimestamps();
}
}
在我的产品资源中:
public function toArray($request)
{
return [
'id'=>$this->id,
'name'=>$this->name,
'description'=>$this->description,
'short_description'=>$this->short_description,
'category'=>$this->category,//category_id
'url'=>$this->url,
'image'=>$this->image,
'relevant'=>$this->relevant,
'month'=>$this->month,
'price'=>$this->price,
'stock'=>$this->stock
];
}
我的迁移清单表:
Schema::create('inventories', function (Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->unsignedInteger('city_id');
$table->timestamps();
$table-> foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
});
我的迁移产品表:
Schema::create('products', function (Blueprint $table)
{
$table->increments('id');
$table ->string('name');
//$table ->integer('stock');
$table ->string('description');
$table ->string('short_description');
$table ->unsignedInteger('category');//category_id
//$table ->integer('price');
$table ->string('url');
$table ->string('image');
$table ->boolean('relevant');
$table ->boolean('month');
$table->timestamps();
$table-> foreign('category')->references('id')->on('categories')->onDelete('cascade');
});
还有我的 inventory_product 迁移表:
$table->increments('id');
$table->integer('inventory_id')->unsigned();
$table->integer('product_id')->unsigned();
$table ->integer('price');
$table ->integer('stock');
$table->timestamps();
$table-> foreign('inventory_id')->references('id')->on('inventories')->onDelete('cascade');
$table-> foreign('product_id')->references('id')->on('products')->onDelete('cascade');
这样,我得到:
{
"id": 1,
//staff on product,
"price": null,
"stock": null
}
我应该得到:
{
"id": 1,
//staff on product,
"price": 123,//data on the pivot table
"stock": 123//data on the pivot table
}
编辑:实际上我应该得到类似的东西:
{
"id": 1,
//staff on product,
[
"inventory_id": 1,//data on the pivot table
"price": 123,//data on the pivot table
"stock": 123//data on the pivot table
]
[
"inventory_id": 2,//data on the pivot table
"price": 333,//data on the pivot table
"stock": 333//data on the pivot table
]
}
如果产品存在多个库存,对吗?
提前谢谢你:)
【问题讨论】:
-
您是否确认任何一种模型的关系都按预期工作?例如。通过在修补程序中运行
Product::first()->inventories()->get()?