【问题标题】:Laravel 5.4 - Eloquent Relationship UpdateLaravel 5.4 - Eloquent 关系更新
【发布时间】:2017-11-20 08:22:47
【问题描述】:

我有一个关于在 Laravel 中更新表格的问题。我有一个 UserCar 模型。示例如下,

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

我可以更新表格,但想知道我是否做得对。

有没有更准确或更好的方法。

【问题讨论】:

    标签: php laravel-5 eloquent


    【解决方案1】:

    当您使用两个模型之间的关系时,最好按照它们在关系中的状态更新它们。所以是的,你几乎是对的。但要了解更多信息,最好在控制器中使用单独的 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();
    }
    

    【讨论】:

    • 感谢您的回答。关于单独的请求文件,您的意思是用不同的方法将它们分开吗?
    • @Khairul 不,我的意思是这样的:php artisan make:request SomethingRequest... 然后你可以在那里修改验证,以获取更多信息:laravel.com/docs/5.5/validation#creating-form-requests .. 希望这有帮助
    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 2017-10-17
    • 2023-03-28
    • 2020-11-21
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多