Laravel 5.4 - Eloquent关联更新

17

我有一个与Laravel相关的更新表格问题。我有一个 UserCar 模型。例如如下:

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);
    }
}

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();
}

我能够更新表格,但想知道我是否做得正确。

有没有更准确或更好的方法可以实现。

1个回答

28

当您在两个模型之间使用关系时,最好更新它们以符合关系。所以是的,你几乎是正确的。但是为了获得更多信息,最好使用与控制器不同的分离的请求文件。还有一件事,根据经验,最好先更新关系。总体而言,它会像这样:

 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();
}

1
谢谢你的回答。关于单独的请求文件,你是指将它们分开放在不同的方法中吗? - Khairul
2
@Khairul 不是这样的,我的意思是:使用 php artisan make:request SomethingRequest 命令创建一个请求类,然后你可以在其中修改验证规则。更多信息请参考:https://laravel.com/docs/5.5/validation#creating-form-requests。希望这能帮到你。 - Alireza Amrollahi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接