【发布时间】:2017-11-20 08:22:47
【问题描述】:
我有一个关于在 Laravel 中更新表格的问题。我有一个 User 和 Car 模型。示例如下,
用户.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $guarded = [];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function cars()
{
return $this->hasMany(Car::class);
}
}
Car.php
<?php
namespace App;
class Car extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
对于更新,我在控制器上使用以下代码,
public function update(Request $request, $id)
{
// validations here
$car = Car::find($id);
$carDetail = Car::where('id', $id)
->update([
'vehicle_no'=> $request->vehicle_no,
'location_id' => $request->location_id,
'created_at' => $request->created_at,
]);
$user = $car->user()
->update([
'name'=> $request->name,
'ic_number'=> $request->ic_number,
]);
return back();
}
我可以更新表格,但想知道我是否做得对。
有没有更准确或更好的方法。
【问题讨论】: