Laravel亲戚用同步方法

时间:2018-05-02 17:08:33

标签: php laravel synchronization

我尝试存储我的产品ID并将它们相互关联,就像将标签附加到帖子上一样。 (基本上只是存储产品的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}}时,它不会返回任何内容。

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

解决

我将我的观看代码更改为以下代码并且现在正在运行:

$relatives = ProductRelative::where('product_id', '=', $product->id)
    ->join('products','products.id', '=', 'relatives_id')->get();

希望它有所帮助。