php - 具有同步方法的 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}}
它不会返回任何内容。
如何解决?
解决方案
解决了
我将我的视图代码更改为下面的代码,它现在可以工作了:
$relatives = ProductRelative::where('product_id', '=', $product->id)
->join('products','products.id', '=', 'relatives_id')->get();
希望能帮助到你。
推荐阅读
- ios - 如果孩子使用环境对象,如何停止刷新视图
- powershell - 在 PowerShell 中从 2 个变量创建递增变量
- html - Python Selenium 从内联的锚点获取链接文本
- algorithm - 为数组中的每个元素查找 k 个最接近的整数
- typescript - 自动导入/类型不适用于我的 NPM 包
- python - 在 Python 中获取 xml 文件中的特定子项
- python - 在 Django 中实现“已保存的书籍”购物车
- snowflake-cloud-data-platform - 是否可以取消设置 Snowflake 任务的 WHEN 条件?
- javascript - IE9:如果字符串的值在对象数组中匹配,则操作字符串
- powershell - Powershell 只输出第一个字符