2016-08-19 99 views
0

我有這段代碼。多對多Ajax Laravel 5.2

public function items($subcategory_id){ 

    $items = $this->ajax->items($subcategory_id); 

    return Response::json([ 
      'success' => 'true', 
      'items' => $items 
     ]); 
} 

,輸出是: enter image description here

正如你可以看到UNIT_ID參考多對多的,你不能操縱它來獲得在JavaScript中UNIT_ID的名稱。我是否需要循環它並創建我自己的數組或者是否有一個函數來完成它。 這是我的存儲庫代碼。

public function items($subcategory_id){ 

    $this->modelName = new Subcategory(); 
    return $this->modelName->find($subcategory_id)->items; 
} 

我的模型

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Subcategory extends Model 
{ 
    protected $table = 'subcategories'; 
    protected $fillable = [ 
     'qty', 'desc', 'unit_price', 'ext_price' 
    ]; 
    public function items(){ 

     return $this->belongsToMany('App\Item', 'item_subcategory', 'subcategory_id', 'item_id')->withTimestamps(); 
    } 
} 
+0

你需要做的是使用預先加載。我不明白你的模型和關係是什麼。發佈您的模型代碼。 – PawelMysior

+0

public function items(){ \t return $ this-> belongsToMany('App \ Item','item_subcategory','subcategory_id','item_id') - > withTimestamps(); } – Rbex

+0

你想發送給JavaScript的json結構是什麼? – KmasterYC

回答

1

使用預先加載。這將與其相關的獲取特定SubcategoryItemsUnits與這些項目:

Subcategory::where('id', $subcategoryId)->with('items.unit')->get(); 
+0

感謝它的魅力。 – Rbex