【发布时间】:2020-12-30 07:50:00
【问题描述】:
看看我的代码
产品迁移
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->string('short_description')->nullable();
$table->text('description');
$table->decimal('regular_price');
$table->decimal('sale_price')->nullable();
$table->string('SKU');
$table->enum('stock_status', ['instock', 'outofstock']);
$table->boolean('featured')->default(false);
$table->unsignedInteger('quantity')->default(10);
$table->string('image')->nullable();
$table->text('images')->nullable();
$table->timestamps();
});
Schema::create('category_product', function (Blueprint $table) {
$table->bigInteger('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->bigInteger('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->primary(['category_id', 'product_id']);
});
}
web.php
Route::get('/product/{slug}', DetailsComponent::class)->name('product.details');
DetailsComponent.php
<?php
namespace App\Http\Livewire;
use App\Models\Product;
use Livewire\Component;
class DetailsComponent extends Component
{
public $slug;
public function mount($slug)
{
$this->slug = $slug;
}
public function render()
{
$product = Product::where('slug', $this->slug)->first();
$popular_products = Product::with('categories')->inRandomOrder()->limit(4)->get();
$related_products = Product::with('categories')
->whereHas('categories')
->where('category_id', $product->category_id)
->inRandomOrder()->limit(5)->get();
return view('livewire.details-component', compact('product', 'popular_products', 'related_products'))->layout('Home.master');
}
}
产品.php
public function categories()
{
return $this->belongsToMany(Category::class);
}
details-component.blade.php
@foreach($related_products as $related_product)
<div class="product product-style-2 equal-elem ">
<div class="product-thumnail">
<a href="{{ route('product.details', ['slug' => $popular_product->slug]) }}" title="{{ $related_product->name }}">
<figure><img src="{{ asset('assets/images/products/'.$related_product->image) }}" width="214" height="214" alt="{{ $related_product->name }}"></figure>
</a>
<div class="group-flash">
<span class="flash-item new-label">new</span>
</div>
<div class="wrap-btn">
<a href="#" class="function-link">quick view</a>
</div>
</div>
<div class="product-info">
<a href="{{ route('product.details', ['slug' => $related_product->slug]) }}" class="product-name"><span>{{ $related_product->name }}</span></a>
<div class="wrap-price"><span class="product-price">${{ $related_product->regular_price }}</span></div>
</div>
</div>
@endforeach
当用户单击链接时,我试图通过使用列 category_id 从数据库中获取特定数据,但出现此错误:
我正在显示产品的类别。我想创建一个类别管理器部分,我已经创建了类别管理器,但是当我提交表单时,我收到如下错误:
【问题讨论】:
-
您的查询构建器中的
where('category_id', $product->category_id)子句正在查询您的products表,而不是您的category_product表。