簡體   English   中英

Laravel 5.4 - 雄辯的關系更新

[英]Laravel 5.4 - Eloquent Relationship Update

我有一個關於更新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();
}

我能夠更新表格,但想知道我是否做得對。

是否有准確或更好的方法。

當你使用兩個模型之間的關系時,如果你在關系中更新它們會更好。 所以,你幾乎是對的。 但是對於更多信息,如果您使用除控制器之外的單獨REQUEST文件,則會更好。 基於經驗的另一件事是,當你首先更新關系時,它會更好。 總的來說,這將是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM