我正在创建一个json来保存具有相同名称(data
)的表单的2个值,以便在表中保存2行而不是同时保存一个。
这个结构是这样创建的,不能编辑。
原则上它是有效的,但最终它给了我一个错误,我不太相信这是一个Laravel问题或只是SQL,所以我不知道去哪里。
我尝试保存值"1"两次查看输出结果,出现以下错误:
SQLSTATE[22018]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]将值nvarchar '["1","1"]'转换为数据类型int时发生错误。(SQL:插入[table_data]([数据])值(("1","1")))
DB和项目本身不能更简单,所以我不知道去哪里,任何想法吗?
DB结构
- ID (INT, Primary Key, AUTOINCREMENT)
- 数据(INT)
DataController.php
namespace AppHttpControllersdata;
use AppData;
use AppHttpControllersController;
use IlluminateHttpRequest;
use AppHttpRequestsStoreDataPost;
class DataController extends Controller
{
public function create()
{
return view('data', ['Data' => new Data()]);
}
public function store(StoreDataPost $request)
{
$json = json_encode($request->get('data'));
Data::create(['data' => $json]);
}
}
Data.php
namespace App;
use IlluminateDatabaseEloquentModel;
class Data extends Model
{
protected $table = 'table_data';
protected $primaryKey = 'ID';
protected $fillable = [
'data'
];
public $timestamps = false;
public function getDataAttribute()
{
return json_decode($this->data);
}
}
StoreDataPost.php
namespace AppHttpRequests;
use IlluminateFoundationHttpFormRequest;
class StoreDataPost extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'data.*' => 'required'
];
}
}
data.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Send Data</title>
</head>
<body>
<form action="{{ route("store") }}" method="POST">
@csrf
{{-- Data in field 1 in DB --}
<div>
<input type="number" name="data[]" id="data">
</div>
{{-- Data in field 2 in DB --}
<div>
<input type="number" name="data[]" id="data">
</div>
<input type="submit" class="btn btn-primary" value="Enviar">
</form>
</body>
</html>
问题是,它试图插入数组内的整数列,试试这个,而不是在你的商店方法的代码:
public function store(StoreDataPost $request)
{
foreach (request('data') as $val) {
Data::create(['data' => $val]);
}
}