【发布时间】:2020-12-11 00:04:26
【问题描述】:
我有两个相似的字段,即我的植物表中的总重量和我的植物物种表中的重量,如下所示
创建植物表
public function up()
{
Schema::create('phytos', function (Blueprint $table) {
$table->id();
$table->string('customer_name');
$table->string('phyto_number');
$table->decimal('total_weight');
$table->date('date_send');
$table->softdeletes();
$table->timestamps();
});
}
创建植物物种表
public function up()
{
Schema::create('phyto_species', function (Blueprint $table) {
$table->id();
$table->integer('phyto_id')->unsigned();
$table->integer('species_id')->unsigned();
$table->integer('destination_id')->unsigned();
$table->integer('preservation_id')->unsigned();
$table->double('weight', 8,2);
$table->softdeletes();
$table->timestamps();
});
}
我一直在尝试使用 array_sum() 作为总重量来求和重量,然后将其分配给如下所示的 'total_weight' => $totalweight] 但是当我保存错误时显示未定义变量:总重量。我想请求帮助
public function store(CreatePhytoRequest $request)
{
$phyto = $this->phytoRepository->create(
['customer_name' => $request->customer_name,
'phyto_number' => $request->phyto_number,
'date_send' => $request->date_send,
'total_weight' => $totalweight]
);
$species = $request->input('species_id', []);
$weight = $request->input('weight', []);
$destination = $request->input('destination_id', []);
$preservation = $request->input('preservation_id', []);
for ($i=0; $i < count($species); $i++) {
if ($species[$i] != '') {
$phyto->species()->attach($species[$i], ['weight' => $weight[$i],'destination_id' => $destination[$i],'preservation_id' => $preservation[$i]]);
}
}
//array_sum work fine
$totalweight = array_sum($weight);
Flash::success('Phyto saved successfully.');
return redirect(route('consignment.phytos.index'));
}
【问题讨论】:
-
我不习惯 laravel 但是你可以分配一个变量而不先创建它吗?因为
$totalweight在您将其分配给total_weight时似乎甚至没有创建。 -
我来宾我是这样做的 $totalweight = array_sum($weight);但是这个声明不可见我不确定如何使它可见可能有正确的方法来声明它可见
-
我的意思是
'total_weight' => $totalweight不是$totalweight甚至没有被声明? -
是的,这是正确的,我寻求帮助