laravel - 使用 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());
}
谢谢,汤姆
解决方案
你可以像这样使用 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
推荐阅读
- r - 拟合广义帕累托模型的阈值
- python - 调用用 Python 编写的 Google Cloud Function 时,Vue 客户端被 CORS 阻止
- python - Python枚举函数自动排序
- android - 扩展功能无法从库中导入
- mysql - 不适用于更新语句的情况
- verilog - 范围规范 Verilog
- c# - 从 Controller .Net Core 返回下载文件
- c++ - 这个函数在c++中执行了多少次
- php - 如何将 PrestaShop 升级到未发布的官方版本,如(1.7.8 或 1.7.7)?
- google-drive-api - 如何将谷歌驱动器菜单栏和/或谷歌幻灯片从英语更改为西班牙语