首页 > 解决方案 > 使用 Laravel/Eloquent 填充数据透视表

问题描述

我有 8 个表:产品、害虫、活性物质、作物、活性产品、害虫产品、作物产品和活性害虫

我已经构建了一个表单,用于加载有关所选(农业化学)产品的信息 - 在该表单中,用户选择与该产品相关的害虫、活性物质和作物。提交时,我现有的代码将预期信息保存在 products 表中,并且通过一组“belongsToMany”关系,active_product、pes_product 和crop_product 数据透视表也正确更新。

我的问题是我不知道如何使用活动和害虫信息(即它们各自的 id 值)来添加/更新 active_pest 表。

我会很感激一些方向。

我的模型中的方法如下:

产品

public function Actives()
{
  return $this->hasMany('App\Models\Active','active_product', 'product_id', 'active_id');
}
public function pest()
{
  return $this->belongsToMany('App\Models\Pest','pest_product', 'product_id', 'pest_id');
}
public function active()
{
  return $this->belongsToMany('App\Models\Active','active_product', 'product_id', 'active_id');
}

积极的

public function product()
{
  return $this->belongsToMany('App\Models\Product', 'active_product', 'active_id', 'product_id');
}

public function pest()
{
  return $this->belongsToMany('App\Models\Pest', 'active_pest', 'active_id', 'pest_id');
}

害虫

public function active()
{
  return $this->belongsToMany('App\Models\Active', 'active_pest', 'pest_id', 'active_id');
}
public function product()
{
  return $this->belongsToMany('App\Models\Product','pest_product', 'pest_id', 'product_id');
}
public function crop()
{
  return $this->belongsToMany('App\Models\Crop','crop_pest', 'pest_id', 'crop_id');
}

我正在使用 BackPack for Laravel - 我的产品控制器包含此更新功能:

public function update(UpdateRequest $request)
{    
    $redirect_location = parent::updateCrud($request);
    return $redirect_location;
}

updateCrud 是

public function updateCrud(UpdateRequest $request = null)
{
    $this->crud->hasAccessOrFail('update');
    $this->crud->setOperation('update');

    // fallback to global request instance
    if (is_null($request)) {
        $request = \Request::instance();
    }

    // update the row in the db
    $item = $this->crud->update($request->get($this->crud->model->getKeyName()),
                        $request->except('save_action', '_token', '_method', 'current_tab', 'http_referrer'));
    $this->data['entry'] = $this->crud->entry = $item;

    // show a success message
    \Alert::success(trans('backpack::crud.update_success'))->flash();

    // save the redirect choice for next time
    $this->setSaveAction();

    return $this->performSaveAction($item->getKey());
}

谢谢,汤姆

标签: laraveleloquentlaravel-backpack

解决方案


你可以像这样使用 laravel 的附加方法:

$actives = App\Active::create([
    'someColumn' => 'test',
    'anotherColumn' => 'test',
]);

$pests = App\Pest::create([
    'someColumn' => 'test',
    'anotherColumn' => 'test',
]);

$actives->pest()->attach($pests);
          ^^^-relation name in model

推荐阅读