我想在laravel上更新相关模型(1到1)时改进这段代码,并且知道这是正确,错误,正确但不推荐等等。谢谢大家。
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->update();
$tenant = Tenant::where('user_id', $id)->first();
$tenant->suite_number = $request->input('suite_number');
$tenant->update();
答案 0 :(得分:1)
首先,您必须在您的用户模型中定义用户和租户的关系:
// User.php
public function tenant()
{
return $this->hasOne('App\Tenant');
}
由于这是一对一型号,您可以更新您的相关型号,如下所示。确保关系模型也存在。
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->tenant->suite_number = $request->input('suite_number');
$user->push();
答案 1 :(得分:0)
我相信它可能是
// you can omit the input() if u want to
$user = User::find($id);
$user->update([
'name' => $request->name;
'email' => $request->email;
]);
$tenant = Tenant::where('user_id', $id)->first();
$tenant->update([
'suite_number' => $request->suite_number;
]);
对于急切加载,它将是
$user = User::with('tenant')->find($id);
$user->update([
'name' => $request->name;
'email' => $request->email;
'tenant.suite_number' => $request->suite_number;
]);
或反向关系
$tenant = Tenant::with('user')->where('user_id', $id)->first();
$tenant->update([
'suite_number' => $request->suite_number;
'user.name' => $request->name;
'user.email' => $request->email;
]);