这是我的购买模式
class Purchase extends Model
{
public function supplierDetails(){
return $this->belongsTo('App\Supplier', 'supplier_id');
}
public function purchasedItems(){
return $this->hasMany('App\PurchasedItem', 'purchase_id');
}
}
这是我的控制器方法
public function getReport(){
$result = Purchase::with('supplierDetails', 'purchasedItems')->get();
return $result;
}
这是我的json结果
[
{
"id": 74,
"supplier_id": 3,
"invoice_no": "wds2",
"supplier_details": {
"id": 3,
"name": "alexy"
},
"purchased_items": [
{
"id": 114,
"purchase_id": 74,
"item_id": 2
},
{
"id": 115,
"purchase_id": 74,
"item_id": 3
}
]
}
]
我可以在这三个模型“ Supplier”,“ Purchase”和“ PurchaseItem”之间建立关系,但不能与“ Item”模型建立关系
我想要这样的json响应
[
{
"id": 74,
"supplier_id": 3,
"invoice_no": "wds2",
"supplier_details": {
"id": 3,
"name": "alexy"
},
"purchased_items": [
{
"id": 114,
"purchase_id": 74,
"item_id": 2,
"item_details": {
"id": 2,
"name": "item1"
}
},
{
"id": 115,
"purchase_id": 74,
"item_id": 3,
"item_details": {
"id": 3,
"name": "item2"
}
}
]
}
]
有什么主意吗?
答案 0 :(得分:2)
这可能会有所帮助,我尚未测试过,但您应该并告诉我。
public function getReport(){
$purchases = Purchase::all;
$result;
foreach($purchases as $p){
$itemsPurchased = $p->purchasedItems;
foreach($itemsPurchased as $pitem){
$pitem['item_details'] = $pitem->YOUR.FUNCTION.NAME.FOR.ITEM.DETAILS.
}
$p['purchased_items'] = $itemsPurchased;
$p['supplier_details'] = $p->supplierDetails;
$result = array($p);
}
return $result;
}
答案 1 :(得分:0)
我做了一些更改,下面的代码起作用了。
public function getAll(){
$array = Purchase::with('supplierDetails', 'purchasedItems')->get();
$purchases = json_decode($array,true);
$result = array();
foreach($purchases as $p){
$itemsPurchased = $p['purchased_items'];
foreach($itemsPurchased as $pitem){
$pitem['item_details'] = PurchasedItem::with('itemDetails', 'packageDetails')->where('purchase_id', '=', $pitem['purchase_id'])->get();
}
$p['supplier_details'] = $p['supplier_details'];
$p['purchased_items'] = $pitem['item_details'];
array_push($result, array($p));
}
return $result;
//[0] added to remove []sqauare bracket
}