我试着存储我的产品id,并将它们相互关联,就像你在帖子上贴标签时一样。(基本上只是储存产品的标识,仅此而已)
问题
当我试图保存我的产品时,我会得到这个错误。
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'product_relative_id' in 'field list' (SQL: select `product_relative_id` from `product_relatives` where `product_id` = 46)代码
schema
public function up()
{
Schema::create('product_relatives', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->integer('relatives_id')->unsigned();
});
Schema::table('product_relatives', function (Blueprint $table) {
$table->foreign('product_id')->references('id')->on('products');
$table->foreign('relatives_id')->references('id')->on('products');
});
}ProductRelative model
class ProductRelative extends Model
{
public $timestamps = false;
protected $table = 'product_relatives';
public $fillable = ['product_id', 'relatives_id'];
public function product()
{
return $this->belongsTo(Product::class, 'product_relatives');
}
}Product model
public function relatives()
{
return $this->belongsToMany(ProductRelative::class, 'product_relatives');
}Store method
//load other products in create page
public function create()
{
$relatives = Product::all();
return view('admin.products.create', compact('relatives'));
}
//storing new product
public function store(Request $request)
{
//validation etc.
$product->save();
$product->relatives()->sync($request->relatives, false);
return redirect()->route('products.show',$product->id);
}blade
{{ Form::label('relatives', 'Relative Products') }}
<select data-placeholder="Select a Relative product" class="form-control tagsselector" id="relatives" name="relatives[]" multiple="multiple">
@foreach($relatives as $relative)
<option value="{{ $relative->id }}">{{ $relative->title }}</option>
@endforeach
</select>问题
为什么我会得到错误,如何解决呢?
更新
我已经将我的product model更改为下面的代码,它现在正在工作。
public function relatives()
{
return $this->belongsToMany(ProductRelative::class, 'product_relatives', 'product_id', 'relatives_id');
}新发行
现在,我可以保存我的相关产品,我有一个困难的时间返回他们在我的看法。
迄今为止:
我将此代码添加到视图函数中:
$relatives = ProductRelative::where('product_id', '=', $product->id)->get();并将此代码添加到我的视图中:
@foreach($relatives as $relative)
{{$relative}}
@endforeach这样我就能得到如下的结果:
{"id":3,"product_id":36,"relatives_id":2} {"id":5,"product_id":36,"relatives_id":25} 但是,当我将刀片代码更改为{{$relative->title}}时,它不会返回任何内容。
怎么解决这个问题?
发布于 2018-05-02 18:11:04
解出
我将视图代码更改为下面的代码,它现在起作用了:
$relatives = ProductRelative::where('product_id', '=', $product->id)
->join('products','products.id', '=', 'relatives_id')->get();希望能帮上忙。
https://stackoverflow.com/questions/50140061
复制相似问题