我有一个表命名为product.product表由productcode字段组成 在添加产品时,我需要按照产品代码字段的顺序生成代码PRO-1,PRO-2,PRO-3,并且必须以以下形式加载
答案 0 :(得分:0)
我已经在我的产品模型中创建了函数,并成功完成了此操作
public static function generateSeriesNumberWithPrefix($tableName = '', $autogenField = '', $autogenStart = '', $autogenPrefix = '')
{
$listFiledValues = DB::table($tableName)->select($autogenField)->get();
if ($listFiledValues->isEmpty())
{
$generatedAutogen = $autogenPrefix.$autogenStart;
return $generatedAutogen;
}
elseif ($listFiledValues->isNotEmpty())
{
foreach($listFiledValues as $listFiledValue)
{
$eachListarray = $listFiledValue->$autogenField;
$totalListArrays[] = $eachListarray;
}
foreach($totalListArrays as $totalListArray)
{
$stringRemovedEachListArray = substr($totalListArray,strlen($autogenPrefix));
$stringRemovedTotalListArray[] = $stringRemovedEachListArray;
}
$maximumValue = max($stringRemovedTotalListArray);
$generatedAutogen = $autogenPrefix.++$maximumValue;
return $generatedAutogen;
}
}
最后在create函数中
public function create ()
{
$autogen = Product::generateSeriesNumberWithPrefix('product','autogen','1','PRO-');
return view('product.formadd', compact('result','sequence'));
}
我正在使用Laravel表单构建器,所以
{!! Form::text('productcode', $autogen, null, ['class' => 'form-group']) !!}
此处generateSeriesNumberWithPrefix
是函数名,Product is a Model Name
此函数的主要优点是它不依赖于其他字段,例如created_at
或primary key
中的最大值,它是独立函数