如何在laravel的第3个表中保存子属性 [英] How to save sub attribute in 3rd table in laravel
问题描述
我想将sub-attribute
数据保存在3rd
表中,但出现Call to undefined method App\Product::mores()
错误.
I want to save my sub-attribute
data in 3rd
table but i got Call to undefined method App\Product::mores()
error.
获取product_id
+获取submore_id
将其保存到product_mores
表中.
Getting product_id
+ getting submore_id
save it to product_mores
table.
问题是我不想获得more_id
,但是我想获得submore_id
.
The issue is that I don't want to get more_id
but instead I want to get submore_id
.
- 更多= CPU
- Submore =酷睿i7
- Product_id = 67
结果将类似于:
通常我应该保存属性ID,并且使用这样的东西会很容易:
Normally i should save attribute id and that would be easy with something like this:
$product->mores()->sync($request->mores, false);
保存产品但后,我需要提供submore
id,但出现错误,并显示:
after saving product BUT as I need to gave submore
id I get error and it says:
Call to undefined method App\Product::mores()
这导致我:
$product->mores()->sync($request->mores, false);
代码
创建方法:
Codes
create method:
public function create()
{
$categories = Category::all();
$subcategories = Subcategory::all();
$submores = Submore::all();
$user = Auth::user();
$brands = Brand::all();
return view('admin.products.create', compact('user', 'categories', 'subcategories', 'submores', 'brands'));
}
存储方法:
//......
$product->save();
$product->mores()->sync($request->mores, false);
//Display a successful message upon save
Session::flash('flash_message', 'Product, '. $product->title.' created');
return redirect()->route('products.index');
创建刀片页面:
<label for="mores">Attributes</label>
<select class="tagsselector form-control" name="mores[]" multiple="multiple">
<option>Select Attribute</option>
@foreach($submores as $more)
<option value="{{ $more->id }}">{{ $more->title }}</option>
@endforeach
</select>
有什么主意吗?
推荐答案
已解决
我所需要做的就是在模型函数中添加表名和列名,如下所示:
SOLVED
All I needed was to add table and column names in my models functions like so:
public function submores()
{
return $this->belongsToMany(Submore::class, 'product_mores', 'product_id', 'submore_id');
}
然后将我的保存功能从mores
更改为submores
,如下所示:
And also change my save function from mores
to submores
like so:
$product->submores()->sync($request->submores, false);
然后将我的表单中的name
和for
更改为submores
Then change the name
and for
in my form to submores
<label for="submores">Attributes</label>
<select class="tagsselector form-control" name="submores[]" multiple="multiple">
//// rest of the code...
这篇关于如何在laravel的第3个表中保存子属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!