这是我的代码:
$num = 5;
$voucher = new Voucher;
for ( $i = $num; $i > 0; $i-- ) {
$token = generateRandomString(5, ['number', 'uppercase']);
$voucher->prefix = $request->prefix;
$voucher->token = $token;
$voucher->description = $request->description;
$voucher->date_time = time();
$voucher->save();
}
显然我的代码应插入5行。但令人惊讶的是它只插入了一行。怎么了?我该怎么办呢?
答案 0 :(得分:2)
您始终使用对象的相同实例。每次使用不同的数据保存同一行时。这是如何修复。
function wavelist()
wavefiles=dir('*.wav'); % loaded wave files
myfolder='/home/adspr/Desktop/exps_sree/waves/selectedfiles'; %Output folder to store files
for i=1: numel(wavefiles) %for each wave file
filename=wavefiles(i).name;
[~,name,~] = fileparts(filename); % found the name of file without extension
a=name(end-2:end); %get the last 3 digits in the file name
fileID = fopen('nameslist','r');
while ~feof(fileID)
b=fgetl(fileID); % get each line in the list file
if strcmp(a,b) % compare
movefile(filename,myfolder); % moved to otput folder
end
end
fclose(fileID);
end
end
答案 1 :(得分:1)
您应该在for循环中创建一个新凭证。目前,正如您所说,您将同一个对象插入数据库五次
答案 2 :(得分:1)
您每次都在使用相同的实例! 在每个for循环中创建一个新的,如:
$num = 5;
for ( $i = $num; $i > 0; $i-- ) {
$voucher = new Voucher;
$token = generateRandomString(5, ['number', 'uppercase']);
$voucher->prefix = $request->prefix;
$voucher->token = $token;
$voucher->description = $request->description;
$voucher->date_time = time();
$voucher->save();
}
答案 3 :(得分:1)
这是创建多数组的基本示例,只需插入插入函数即可。
$num = 5;
$dataArray = array();
for ( $i = $num; $i > 0; $i-- ) {
$token = generateRandomString(5, ['number', 'uppercase']);
$dataArray[$i]['prefix'] = $request->prefix;
$dataArray[$i]['token'] = $token;
$dataArray[$i]['description'] = $request->description;
$dataArray[$i]['date_time'] = time();
}
Voucher::insert($dataArray);
答案 4 :(得分:0)
如果您已有模型实例,则可以使用fill
方法使用一组属性填充它:
$num = 5;
$voucher = new Voucher;
for ( $i = $num; $i > 0; $i-- ) {
$token = generateRandomString(5, ['number', 'uppercase']);
$payload = [];
$payload['prefix'] = $request->prefix;
$payload['token'] = $token;
$payload['description'] = $request->description;
$payload['date_time'] = time();
$voucher->fill($payload);
}