2015-11-16 27 views
0

我正在尋找一種方式將模型作爲JSON返回,其中包括保存後的關聯模型(控制器內)。Laravel返回一個模型+關聯作爲JSON

我知道如何爲JSON與各協會通過執行以下回應:

$objects = MyModel::with(['assocation1', 'association2.dependencies'])->get(); 
return response()->json($objects, 200); 

但是在對象的情況下,已經發現了什麼?我試圖使用與上面相同的概念,但它返回每一行。

$object = MyModel::first(); 
$object->with(['assocation1', 'association2.dependencies'])->get(); 

不幸的是,Laravel的文檔對此有很多說明。我正在試圖做的是返回一個JSON對象包括關聯保存後,在控制器內:

class ExampleController extends Controller { 
    public function store() 
    { 
     $object = new MyModel($request->input('object')); 
     $response = DB::transaction(function() use ($object) { 
      if (object()->save()) { 
       // Here I want to return the object with association1 as JSON 
       return response()->json($object->with('association1')->get(), 201); 
      } 
     }); 
     return $response; 
    } 
} 

編輯

更多澄清這種情況。使用withload似乎會產生相同的結果:返回Object對象的所有行,包括關聯。我的目標是隻返回一個與JSON關聯的對象,而不是全部。

+0

你能說得更清楚嗎? –

回答

0

我相信你並沒有你想像的那麼遙遠。在你的第二個例子中,你不應該調用get()。試試這個:

if ($object = $object->save()) 
{ 
    $object->load(['assocation1', 'association2.dependencies']); 
    return response()->json($object, 201); 
} 
+0

它的作品!正如你所說,我並沒有那麼遠。謝謝 – lkartono

相關問題