我有两张桌子
产品:ID,代码,详细信息,created_at
price_revision :ID,PRODUCT_ID,revised_price,用户,备注,created_at,的updated_at
我想制作以下json:
{
"accessory_price":{[
"date":"2015-03-01",
"products":
{[ "product_id":1, "product_name":"test accessory 1", "revised_price":50.00, "user":"samyak", "remarks":"n/a" ], [ "product_id":2, "product_name":"test accessory 2", "revised_price":60.00, "user":"samyak", "remarks":"n/a" ], [ "product_id":3, "product_name":"test accessory 3", "revised_price":70.00, "user":"samyak", "remarks":"n/a" ]}
],
[
"updated_at":"2015-02-01",
"products":
{[ "product_id":1, "product_name":"test accessory 1", "revised_price":40.00, "user":"sam", "remarks":"n/a" ], [ "product_id":2, "product_name":"test accessory 2", "revised_price":50.00, "user":"sam", "remarks":"n/a" ], [ "product_id":3, "product_name":"test accessory 3", "revised_price":60.00, "user":"sam", "remarks":"n/a" ]}
]
]}
我做了这样的模型:
产品型号
public function productpricerevision(){
return $this->hasMany('Modules\Quotes\Entities\ProductPriceRevision','product_id');
}
存储库代码
public function getProductPrice(){
$productprice=ProductModel::with('productpricerevision')->get();
$data=array('accessory_price'=>$productprice);
return $data;
}
但是这个代码我得到了
{
"product_price": [
{
"id": 1,
"code": "G4007",
"detail": "Flyscreen Gasket -4007",
"created_at": "2014-07-11 13:53:02",
"productprice": [
{
"id": 1,
"product_id": 1,
"revised_price": 78,
"user": "sam",
"remark": "test",
"created_at": "2016-03-30 00:00:00",
"updated_at": "2016-03-30 00:00:00"
}
]
},
{
"id": 2,
"code": "CZBR-100S",
"detail": "Single Bearing Roller BR-100-S",
"created_date": "2014-07-11 13:57:15",
"productprice": [
{
"id": 4,
"product_id": 2,
"revised_price": null,
"user": sam,
"remark": null,
"created_at": "2016-03-30 00:00:00",
"updated_at": "2016-03-30 00:00:00"
}
]
},
产品迁移
class CreateProductsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function(Blueprint $table)
{
$table->integer('id');
$table->string('code', 25);
$table->text('detail', 65535)->nullable();
$table->timestamp('created_date')->default(DB::raw('CURRENT_TIMESTAMP'));
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('products');
}
}
price_revision
public function up()
{
Schema::create('product_price_revision', function(Blueprint $table)
{
$table->increments('id');
$table->integer('product_id');
$table->double('revised_price')->nullable();
$table->string('user')->nullable();
$table->text('remark')->nullable();
$table->foreign('product_id')->references('id')->on('products')->onDelete('CASCADE')->onUpdate('CASCADE');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('product_price_revision');
}
我也尝试了其他几种方法,但最后我迷路了。任何帮助表示赞赏。