【问题标题】:error occured when save data using hasmany relationnship in laravel在laravel中使用hasmany关系保存数据时出错
【发布时间】:2018-09-10 01:39:33
【问题描述】:

vehicle模型中创建hasmany关系,并在vehicle和vehicle_staff表中插入数据。数据成功插入到车辆表中,但是当存储在vehicle_staff 中时出现以下错误。

错误来了:

类型错误:参数 1 传递给 Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() 必须是 Illuminate\Database\Eloquent\Model 的实例,给定数组,调用 E:\xampp\htdocs\laravel-projects\collegeaccounting\app\Http\Controllers\Transport\VehicleController.php 第 53 行

车辆员工表架构:

Schema::create('vehicle_staffs', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->unsignedInteger('vehicles_id');
            $table->unsignedInteger('staffs_id');

            $table->boolean('status')->default(1);
        });

与车型有很多关系:

 class Vehicle extends BaseModel
{
    protected $fillable = ['created_by', 'last_updated_by', 'number', 'type', 'model', 'description', 'status'];

    public function staff(){
        return $this->hasMany(Staff::class);
    }
}

商店功能:

public function store(AddValidation $request)
    {
        $request->request->add(['created_by' => auth()->user()->id]);

        $vehicle =  Vehicle::create($request->all());

        if ($request->has('staffs_id')) {
            $staffs = [];
            foreach ($request->get('staffs_id') as $staff) {
                $staffs[$staff] = ([
                    'vehicles_id' => $vehicle->id,
                    'staffs_id' => $staff
                ]);
            }

            $vehicle->staff()->save($staffs);
        }

        $request->session()->flash($this->message_success, ' Created Successfully.');
        return redirect()->route($this->base_route);
    }

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    看来你是在创建many to many relationships,也就是说一个车可以属于很多员工,一个员工可以有很多车。所以,vehicle_staffsvehicle 模型和staff 模型之间的中间表(或数据透视表)。

    对于Vehicle模型,您应该将人员方法更改为:

    public function staff(){
        return $this->belongsToMany(Staff::class, 'vehicle_staffs', 'vehicles_id', 'staffs_id');
    }
    

    要更新many to many relationships,您可以将员工ID附加到车辆:

    $vehicle->staff()->attach($staffIds);
    

    以及您的商店功能的代码更改:

    if ($request->has('staffs_id')) {
        $staffIds = $request->get('staffs_id');
        $vehicle->staff()->attach($staffIds);
    }
    

    【讨论】:

    • 确实,必须添加数据透视表、外键和本地键,因为设置不遵循雄辩的约定。没关系,只要你给 laravel 它需要的信息。作为一种好的做法,我也用来创建反向关系。在 Staff.php 模型中添加与车辆的关系() return $this->belongsToMany(Vehicle::class, 'vehicle_staffs', 'staffs_id', 'vehicles_id');
    • 感谢您的出色回答。添加 $vehicle->staff()->attach($staffIds);美好的。你能解释一下更新案例吗?
    • 继续阅读文档 (laravel.com/docs/5.6/…),您应该会看到 Syncing Associations,使用 sync 而不是 attach 应该会更新多对多关系
    【解决方案2】:

    我不知道您使用的是哪个版本的 Laravel,所以我假设您使用的是 Laravel 5.x。

    如果你想保存多个对象,你应该使用saveMany()。它接受一个集合或模型数组作为参数。

    来自the documentation

    如果需要保存多个相关模型,可以使用saveMany方法:

    $post = App\Post::find(1);
    
    $post->comments()->saveMany([
        new App\Comment(['message' => 'A new comment.']),
        new App\Comment(['message' => 'Another comment.']),
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      相关资源
      最近更新 更多