如何获取新创建的联系人模型的相关用户表,然后在响应标题content-length out将其放到json()中。新创建的模型与相关的表输出,然后到json
public function store(Request $request) {
try {
$contact = new Contact();
$contact->email_address = Helper::strip_tags($request->get('email_address'));
$contact->firstname = ucfirst($request->get('firstname'));
$contact->lastname = ucfirst($request->get('lastname'));
$contact->company = ucfirst($request->get('company'));
$contact->phone = $request->get('phone');
$contact->mobile = $request->get('mobile');
$contact->description = Helper::strip_tags($request->get('description'));
if($contact->save()) {
// here is the part I'm having trouble with
$contact = $contact->with('user')->get();
return response()->json($contact, 200, ['Content-Length' => strlen($contact->toJson())]);
} else {
return response()->json(array('error' => true, 'messages' => $contact->errors), 400);
}
} catch(Exception $e) {
return response()->json(array('error' => true, 'type' => 'exception', 'message' => $e->getMessage()), 500, ['Content-Length' => $e->getMessage()]);
}
解决方案如下:
正如你已经加载的模型(创建时),你不会使用with
,因为它是预先加载的关系。
如果我理解你的问题正确,得到User
关系包括在输出中,你就可以用“懒预先加载”所以你会做$contact->load('user');
希望这有助于!