<input type="text" name="subcat[0]">
<input type="text" name="subcat[1]">
<input type="text" name="subcat[2]">
<input type="text" name="subcat[3]">
这些是我的模特:
在类别模型
中public function subcategories()
{
return $this->hasMany('App\SubCategory','subcategories_id');
}
子类别模型
public function category()
{
return $this->belongsTo('App\Category' ,'categories_id');
}
控制器
$s = Input::get('subcat');
$input = request('category');
$id = Category::where('CategoryName', $input)->pluck('id');
$subcat = [];
$category=Category::find($id );
foreach ($s as $item ) {
$item->category()->associate($category);
$item->save();
}
我收到错误&#34;在字符串上调用成员函数category():&#34;
答案 0 :(得分:0)
$item
是您输入的字符串(我猜它必须是子类别的名称)。您应该首先创建子类别。
我认为你应该替换:
foreach ($s as $item ) {
$item->category()->associate($category);
$item->save();
}
人:
foreach ($s as $item) {
// Get sub category by name or create a new subcategory
$sub_cat = SubCategory::where('SubCategoryName', $item)->first();
if (!$sub_cat) {
$sub_cat = new \App\SubCategory();
$sub_cat-> SubCategoryName = $item; // <-- replace "SubCategoryName" by
// the property you need
// to update from input
$sub_cat->save();
}
$category->subcategories()->save($sub_cat);
}
答案 1 :(得分:0)
$s
是字符串数组。
你的for循环可以写成
foreach ($s as $item ) {
$sub = SubCategory::where('SubCategoryName', $item)->first();
$sub->category()->associate($category);
$sub->save();
}