【发布时间】:2020-02-16 21:16:40
【问题描述】:
在我的应用中,我有 Product 和 ProductCategory 模型,一个 ProductCategory 有许多产品,一个产品属于一个 ProductCategory,在我的种子文件中,我成功地创建了类别及其产品。
现在问题出在我的控制器中,我正在尝试使用预先加载方法来加载所有产品类别及其各自的产品,如下所示:
$productCategories = ProductCategory::with('products')->get();
但是我收到以下错误消息:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.product_category_id' in 'where clause' (SQL: select * from `products` where `products`.`product_category_id` in (1, 2, 3, 4))
这些是我的模型:
产品:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'products';
public function productcategory()
{
return $this->belongsTo('App\Models\ProductCategory', 'productcategory_id');
}
}
产品类别:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProductCategory extends Model
{
protected $table = 'productcategories';
public function products()
{
return $this->HasMany('App\Models\Product');
}
}
现在我的迁移:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('productcategory_id')->index();
$table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade')->onUpdate('cascade');
$table->string('title');
$table->timestamps();
});
}
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::dropIfExists('products');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductCategoriesTable extends Migration
{
public function up()
{
Schema::create('productcategories', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->unique();
$table->timestamps();
});
}
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::dropIfExists('productcategories');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
}
【问题讨论】:
-
你输入了
productcategory_id和product_category_id
标签: javascript php laravel vue.js