【发布时间】:2016-08-22 00:43:07
【问题描述】:
我正在使用 Laravel 5.1
我想在我的数据库中保存动态创建输入的输入值。
我基本上用这条线创建动态输入:
...
for(var i = 1; i<slider.value; i++) {
+'<div class=\"input-group\">'
+'<input name=\"input-chapter-name[]\" name="" type=\"text\">'
+'<input name=\"input-chapter-start[]\" name="" type=\"text\">'
+'<input name=\"input-chapter-end[]\" name="" type=\"text\">'
+'</div>'
}
我的两个模型如下所示:
<?php
class Chapters extends Model
{
protected $table = 'chapters';
protected $fillable = ['chapter_name' ,'input-chapter-start', 'input-chapter-end'];
public function product()
{
return $this->belongsTo('App\Product');
}
}
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['email', 'title', 'filename', 'inputMpg', 'number_of_chapters'];
public static $rules = [
'email' => 'required|email|max:50',
'title' => 'required|max:50',
'filename' => 'required|max:50',
'input_mpg' => 'required',
'number_of_chapters' => 'required',
'input-chapter-name' => 'required',
'input-chapter-start' => 'required',
'input-chapter-end' => 'required'
];
public function Chapters()
{
return $this->hasMany('App\Chapters');
}
}
在我的控制器中,我保存(尝试保存)这样的数据:
$product->save();
$Chapters->chapters;
$Chapters->product()->associate($product);
$Chapters->save();
并得到以下错误:
Grammar.php 第 118 行中的 ErrorException:参数 1 传递给 Illuminate\Database\Grammar::parameterize() 必须是数组类型, 给定整数,调用 C:\xampp\htdocs\lariApp\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php 在第 672 行并定义
编辑:
我当前的控制器如下所示:
<?php
class ProductController extends Controller
{
protected $request;
public function request(Request $request)
{
$this->request = $request;
}
public function createProduct(Request $request, $productID)
{
$product = new Product;
$data = $request->only('email', 'title', 'filename', 'number_of_chapters');
# Validate Input
$validator = Validator::make($request->all(), Product::$rules);
# if validation fails return Erros
if($validator->fails())
{
return Redirect::back()->withInput()->withErrors($validator);
}
$product->fill($data);
if($product->save())
{
$product = Product::find($productID);
foreach ($request->input('chapters', []) as $chaptersData) {
$chapters = new Chapters($chaptersData);
$chapters->product()->associate($product);
$chapters->save();
}
return redirect()->route('root')->with('message', 'WIN')->withInput();
}
else
{
return redirect()->route('newProduct')->with('message', 'Error')->withInput();
}
}
}
还有我的路线:
Route::post('create/{productID}', ['as' => 'createProduct', 'uses' => 'ProductController@createProduct']);
【问题讨论】:
-
118行是$chapters->product()->associate($product);行吗? -
控制器中的 4 行没有意义。这肯定是个问题,不知道你想做什么。
-
不,第 118 行不是那行
标签: mysql laravel dynamic input laravel-5