Php Laravel 5.4-雄辩的关系更新
我对更新Laravel中的表有一个问题。我有一个Php Laravel 5.4-雄辩的关系更新,php,laravel-5,eloquent,Php,Laravel 5,Eloquent,我对更新Laravel中的表有一个问题。我有一个用户和汽车型号。举例如下: User.php <?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; protected $guarde
用户
和汽车
型号。举例如下:
User.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);
}
}
<?php
namespace App;
class Car extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
我可以更新表格,但想知道我是否做得对
有没有一种准确或更好的方法可以做到这一点。当您使用两个模型之间的关系时,最好按照它们在关系中的状态进行更新。是的,你几乎是对的。但是为了获得更多信息,最好使用单独的请求文件,而不是在控制器中。根据经验还有一件事,首先更新关系会更好。总的来说是这样的:
public function update(SomeRequestFile $request, $id)
{
$car = Car::find($id);
$user = $car->user()
->update([
'name'=> $request->name,
'ic_number'=> $request->ic_number,
]);
$carDetail = Car::where('id', $id)
->update([
'vehicle_no'=> $request->vehicle_no,
'location_id' => $request->location_id,
'created_at' => $request->created_at,
]);
return back();
}
谢谢你的回答。关于单独的请求文件,您是想用不同的方法将它们分开吗?@Khairl否,我的意思是:php artisan make:RequestsomethingRequest。。。然后您可以在那里修改验证,以获取更多信息:。。希望这有帮助
public function update(SomeRequestFile $request, $id)
{
$car = Car::find($id);
$user = $car->user()
->update([
'name'=> $request->name,
'ic_number'=> $request->ic_number,
]);
$carDetail = Car::where('id', $id)
->update([
'vehicle_no'=> $request->vehicle_no,
'location_id' => $request->location_id,
'created_at' => $request->created_at,
]);
return back();
}