CRUD Laravel更新数据库一对多关系

如何解决CRUD Laravel更新数据库一对多关系

我有一个带有汽车的CRUD应用程序,对于每辆汽车,我都有创建汽车的字段和要上传的图像。一切都好,我有一对多的关系,对于一辆汽车,我可以有多个图像。当我创建汽车并上传照片时,这些照片会正确存储在数据库中以及我的公共/图像主管中。问题是当我想使UPDATE成为标准参数时,我不知道如何更新数据库中的照片。

这是我的代码,我具有更新功能,我不知道该如何进行更新。

My cars table:

    Schema::create('cars',function (Blueprint $table) {
            $table->id();
            $table->string('model');
            $table->integer('seats');
            $table->string('fuel');
            $table->integer('year');
            $table->string('color');
            $table->string('gearbox');
            $table->integer('price');
            $table->string('coinType');
            $table->timestamps();
        });


My images table

    Schema::create('images',function (Blueprint $table) {
            $table->id();
            $table->integer('car_id');
            $table->string('file_name');
            $table->timestamps();
        });


My Car model:

    class Car extends Model
{
    protected $fillable = [
        'model','seats','fuel','year','color','gearbox','price','coinType',];

    public function images()
    {
        return $this->hasMany(Image::class);
    }
    use HasFactory;
}

My Image model:

    class Image extends Model
{
    protected $fillable = [
        'car_id','file_name'
    ];
    
    public function car()
    {
        return $this->belongsTo(Car::class);
    }
    use HasFactory;
}


My edit.blade:

    @extends('layouts.app')

@section('content')
<div class="row">
    <div class="col-sm-8 offset-sm-2">
        <h2 class="display-3">Edit a car</h2>
        <div>
            @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div><br />
            @endif
            <form method="post" action="{{ url('cars/'. $res->id) }}" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <div class="form-group">
                    <legend>
                        <label for="model" class="col-form-label">Model :</label>
                        <input type="text" class="form-control" id="model" name="model" value="{{ $res->model }}">
                    </legend>
                </div>

                <div class="form-group ">
                    <legend>
                        <label for="seats" class="col-form-label">Seats :</label>
                    </legend>
                    <select name="seats" id="seats" value="{{ $res->seats }}">
                        <option value="2">2</option>
                        <option value="4" selected="selected">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                    </select>
                </div>

                <div class="form-group ">
                    <legend>
                        <label for="fuel" class="col-form-label">Fuel :</label>
                    </legend>
                    <select name="fuel" id="fuel" value="{{ $res->fuel }}">
                        <option value="benzine+gpl">benzine+gpl</option>
                        <option value="gpl" selected="selected">diesel</option>
                        <option value="diesel">gpl</option>
                        <option value="diesel+gpl">diesel+gpl</option>
                        <option value="benzine">benzine</option>
                    </select>
                </div>

                <div class="form-group ">
                    <legend>
                        <label for="year" class="col-form-label">Year :</label>
                    </legend>
                    <input type="text" name="year" id="year" value="{{ $res->year }}">
                </div>

                <div class="form-group">
                    <legend>
                        <label for="color" class="col-form-label">Color :</label>
                    </legend>
                    <input type="text" class="form-control" id="color" name="color" value="{{ $res->color }}">
                </div>

                <div class="form-group ">
                    <legend>
                        <label for="gearbox" class="col-form-label">Gearbox :</label>
                    </legend>
                    <select name="gearbox" id="gearbox" value="{{ $res->gearbox }}">
                        <option value="manual">manual</option>
                        <option value="automatic" selected="selected">automatic</option>
                        <option value="semiautomatic">semiautomatic</option>
                    </select>
                </div>

                <div class="form-group ">
                    <legend>
                        <label for="price" class="col-form-label">Price :</label>
                    </legend>
                    <input type="text" class="form-control" id="price" name="price" value="{{ $res->price }}">
                </div>

                <div class="form-group ">
                    <legend>
                        <label for="coinType" class="col-form-label">CoinType :</label>
                    </legend>
                    <select name="coinType" id="coinType" value="{{ $res->coinType }}">
                        <option value="EUR">EUR</option>
                        <option value="LEI" selected="selected">LEI</option>
                        <option value="USD">USD</option>
                    </select>
                </div>

                <div class="form-group ">
                    <legend>
                        <label for="image" class="col-form-label">Upload images :</label>
                    </legend>
                    <input type="file" class="form-control" name="images[]" multiple />
                </div>


                <hr style="height:2px;border-width:0;color:gray;background-color:gray">

                <div class="col-xs-12 col-sm-12 col-md-12 ">
                    <button type="submit" class="btn btn-primary">Add car</button>
                    <a class="btn btn-primary" href="{{ route('cars.index') }}"> Back</a>
                </div>
        </div>
        </form>

        @endsection

我的控制器:

public function store(Request $request)
{
    $request->validate([
        'model' => 'required','year' => 'required','color' => 'required','price'=> 'required','file_name.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    $destionationPath = public_path('/images');
    $images = [];

    $car = new Car();
    $car->model = $request->model;
    $car->seats = $request->seats;
    $car->fuel = $request->fuel;
    $car->year = $request->year;
    $car->color = $request->color;
    $car->gearbox = $request->gearbox;
    $car->price = $request->price;
    $car->coinType = $request->coinType;
  

    $car->save();

    
    if ($files = $request->file('images')) {
        foreach ($files as $file) {
            $fileName = $file->getClientOriginalName();
            $file->move($destionationPath,$fileName);
            $images[] = $fileName;
        }
    }

    foreach ($images as $imag) {
        $image = new Image();
        $image->car_id = $car->id;
        $image->file_name = $imag;
        $image->save();
    }


    return redirect()->route('cars.index')->with('success','Car saved !');
}

public function update(Request $request,$id)
{
    $request->validate([
        'model' => 'required',svg|max:2048'
    ]);

    $destionationPath = public_path('/images');
    $images = [];

    $car = Car::find($id);
    $car->model = $request->model;
    $car->seats = $request->seats;
    $car->fuel = $request->fuel;
    $car->year = $request->year;
    $car->color = $request->color;
    $car->gearbox = $request->gearbox;
    $car->price = $request->price;
    $car->coinType = $request->coinType;
  

    $car->update();

    
    if ($files = $request->file('images')) {
        foreach ($files as $file) {
            $fileName = $file->getClientOriginalName();
            $file->move($destionationPath,$fileName);
            $images[] = $fileName;
        }
    }

    foreach ($images as $imag) {
        //here I don't know what to do
    }


    return redirect()->route('cars.index')->with('success','Car updated !');
}

谢谢。

解决方法

在查看刀片文件时,您并没有真正显示原始图像,因此用户无法更新图像,他可以插入新图像并且应该删除旧图像,对吗?

如果要更新图像,则必须在刀片文件上显示具有ID的原始图像,因此在后端可以根据ID查找图像

但这现在应该对您有用:

您只需检查用户是否上传了任何文件

if ($files = $request->files('images')) {
...

删除所有旧图像

$car->images->each(function($image) {
    // You probabily should be using Storage facade for this
    // this should be the full path,I didn't test it,but if you need add extra methods so it returns the full path to the file
    if (file_exists($destionationPath . '/' . $image->file_name) {
        unset($destionationPath . '/' . $image->file_name);
    }

    $image->delete();
});

然后像在商店中一样重新创建图像

foreach ($files as $file) {
    $fileName = $file->getClientOriginalName();
    $file->move($destionationPath,$fileName);
    $images[] = $fileName;
}

foreach ($images as $imag) {
    $image = new Image();
    $image->car_id = $car->id;
    $image->file_name = $imag;
    $image->save();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-