我使用带有热情包的lavarel。
当我想更新一行时,我遇到了一些问题。
我有 2 个模型 Client 和 Address 相关的 morphone 关系。
这种关系运作良好,当我想获得客户时,此行返回预期结果:
Client::with('address')->find($id);
但我不明白如何用干净的解决方案更新客户端。有人可以回答这些问题:
- 有了 Ardent,你怎么能 autoHydrate 相关模型?
- 当您更新一些数据时, lavarel 的最佳实践是什么?使用更新方法?使用保存?使用推?填充所有模型?使用自动水合物?
当我在我的更新方法中记录 Input::all() 时,我得到了:
[2014-05-31 15:52:56] production.INFO: {"id":983,"firstName":"Susanne","lastName":"Adam","birthDate":"18\/06\/1982","inscriptionDate":"08\/09\/2013","status":3,"created_at":"2014-05-31 14:26:25","updated_at":"2014-05-31 14:26:25","email":"bernard.alix@free.fr","address":{"id":983,"address":"avenue Etienne","address2":"","ville":"Cordierboeuf","cp":"25 10","phone":"0403983157","mobile":"+33 (0)3 0","addressable_id":983,"addressable_type":"Client","created_at":"2014-05-31 14:27:58","updated_at":"2014-05-31 14:27:58"}} [] []
如您所见,地址数据位于客户端数据中。
3.当我使用更新、保存或推送(eloquent的方法)时,eloquent不明白他应该更新Address模型然后更新相关的Client模型。我的数据格式不正确?
谢谢。
更新 :
当我执行 Log::info(Input::all()) 时,我在控制器中得到以下 json 数据:
[2014-06-01 18:10:46] production.INFO: {"id":284,"firstName":"Andr\u00e9e","lastName":"Adam","birthDate":"23\/07\/1944","inscriptionDate":"22\/11\/2013","status":2,"created_at":"2014-06-01 15:41:22","updated_at":"2014-06-01 18:06:44","email":"monique17@normand.com","address":{"id":284,"streetAddress":"93, avenue Lefort","streetAddress2":"","city":"Boulay-sur-Leger","zipCode":"14054","phone":"09 51 03 1","mobile":"+33 6 00 6","addressable_id":284,"addressable_type":"Client","created_at":"2014-06-01 15:42:50","updated_at":"2014-06-01 18:06:44"}} [] []
由于 ardent 的自动水合不起作用......客户端自动水合成功但地址没有,可能是由于它们之间的多态关系(一对一)。
我尝试以这种方式填充我的模型:
$client = Client::with('address')->find($id);
$client->update(Input::except('address'));
$client->address->update(Input::only('address'));
但这不起作用,因为 Input::only('address') 给出了错误的格式数据,当我记录这个时,我得到了:
Log::info(Input::except('address'));
Log::info(Input::only('address'));
//output
[2014-06-01 18:20:34] production.INFO: {"id":284,"firstName":"Andr\u00e9e","lastName":"Adam","birthDate":"23\/07\/1944","inscriptionDate":"22\/11\/2013","status":2,"created_at":"2014-06-01 15:41:22","updated_at":"2014-06-01 18:10:46","email":"monique17@normand.com"} [] []
[2014-06-01 18:20:34] production.INFO: {"address":{"id":284,"streetAddress":"93, avenue Lefort","streetAddress2":"","city":"Boulay-sur-Leger","zipCode":"14054","phone":"09 51 03 1","mobile":"+33 6 00 6","addressable_id":284,"addressable_type":"Client","created_at":"2014-06-01 15:42:50","updated_at":"2014-06-01 18:06:44"}} [] []
所以我混合了两种方法:
$inputs = Input::except('_method');
$client = Client::with('address')->find($id);
$client->update(Input::except('address'));
$client->address->update($inputs['address']);
这工作相当不错!
但是我不明白为什么热心的自动补水失败了……
谢谢。