简体   繁体   English

Laravel 5.4 - 雄辩的关系更新

[英]Laravel 5.4 - Eloquent Relationship Update

I have a question on updating a table in Laravel. 我有一个关于更新Laravel中的表的问题。 I have a User and Car Model. 我有一个UserCar模型。 Example as below, 示例如下,

User.php 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 Car.php

<?php

namespace App;

class Car extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }    
}

For the update, I am using below codes on my controller, 对于更新,我在控制器上使用以下代码,

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

I am able to update the table but want to know if I am doing it right. 我能够更新表格,但想知道我是否做得对。

Is there an accurate or a better way of doing it. 是否有准确或更好的方法。

When you use relation between two models it's better if you update them as they are in the relation. 当你使用两个模型之间的关系时,如果你在关系中更新它们会更好。 so yes you'r almost right . 所以,你几乎是对的。 but for more information it's better if you use separate REQUEST file other than in the controller. 但是对于更多信息,如果您使用除控制器之外的单独REQUEST文件,则会更好。 one more thing based on experience it's better when you update the relation first . 基于经验的另一件事是,当你首先更新关系时,它会更好。 overall it will be something like this : 总的来说,这将是这样的:

 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