【发布时间】:2019-03-04 03:01:39
【问题描述】:
我正在尝试检索所有产品类别及其所有产品,一个产品属于一个产品类别,一个产品类别可以有多个产品。
当我检索 productCategories 时,我收到以下错误:
Illuminate \ Database \ QueryException (42S22)
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))
这是我的产品和类别迁移文件:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ProductsAndCategories extends Migration
{
public function up()
{
//CREATE PRODUCT CATEGORIES TABLE
Schema::create('productcategories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description')->nullable();
$table->string('image')->nullable();
$table->timestamps();
});
// CREATE PRODUCTS TABLE
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('productcategory_id')->index();
$table->foreign('productcategory_id')->references('id')->on('productcategories');
$table->string('title');
$table->string('description')->nullable();
$table->string('body')->default('');
$table->string('image')->nullable()->default(config('globals.dummy_image'));
$table->boolean('isVisible')->default(true);
$table->integer('stockLeft')->default(0);
$table->decimal('halfPrice', 5,2)->default(0.00);
$table->decimal('fullPrice', 5,2)->default(0.00);
$table->decimal('finalPrice', 5,2)->default(0.00);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('products');
Schema::dropIfExists('productcategories');
}
}
还有我的两个相关模型:
产品:
<?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');
}
}
【问题讨论】:
-
Laravel 有进行连接猜测的约定——你的列命名是非标准的。在 Symfony(laravel 的根源)中,TitleCase 类被转换为蛇案例:ProductCategory 变为 product_category,因此在 ProductCategory 的 products() 方法中,除非您将 foreignKey 列指定为 productcategory_id,否则它将尝试暗示蛇案例等效.
-
App\Models\ProductCategory在你的模型中应该只是App\YourModel