首页 > 解决方案 > 具有同步方法的 Laravel 亲戚

问题描述

我尝试存储我的产品 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}}它不会返回任何内容。

如何解决?

标签: phplaravelsynchronization

解决方案


解决了

我将我的视图代码更改为下面的代码,它现在可以工作了:

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

希望能帮助到你。


推荐阅读