I try to store my products id and related them to each other just like when you attach tags to the post. (basically just store id of products nothing more)
Issue
when I try to save my product I get this error
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)
Codes
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>
Question
Why do I get the error and how to solve it?
UPDATE
I've changed my product model
to the code below and it's working now.
public function relatives()
{
return $this->belongsToMany(ProductRelative::class, 'product_relatives', 'product_id', 'relatives_id');
}
New Issue
Now that I can save my related products I have a hard time to return them in my view.
So far:
I added this code to my view function:
$relatives = ProductRelative::where('product_id', '=', $product->id)->get();
and added this code to my view:
@foreach($relatives as $relative)
{{$relative}}
@endforeach
with that I can get result like:
{"id":3,"product_id":36,"relatives_id":2} {"id":5,"product_id":36,"relatives_id":25}
but when I change my blade code to {{$relative->title}}
it does not return anything.
How to fix that?