【发布时间】:2020-05-13 11:18:30
【问题描述】:
我遇到的问题是简单地尝试确定为 Laravel 中用于多对多关系的中间表提供正确的名称。
我在尝试访问 eloquent 关系时收到以下错误:
$product->类别; 使用消息'SQLSTATE [42S02] 照亮/数据库/查询异常:找不到基表或视图:1146 表 'dolstore-laravel.category_product' 不存在(SQL:选择
categories.*、category_product.product_idaspivot_product_id,category_product.category_idaspivot_category_idfromcategoriesinner joincategory_productoncategories.id= @9876543@32@.category_productcategory_productcategory_productcategory_product1)'
我的迁移是这样写的:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create('product_category', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('product_id');
$table->unsignedBigInteger('category_id');
$table->timestamps();
$table->unique(['product_id', 'category_id']);
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
}
似乎我提供了不正确的名称 product_category,而应该是 category_product。管理这个的规则是什么?在另一个例子中,我实际上按照 Laracasts 教程成功,我的迁移是这样写的:
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->timestamps();
});
//Pivot Table
// article_tag
Schema::create('article_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('article_id');
$table->unsignedBigInteger('tag_id');
$table->timestamps();
$table->unique(['article_id', 'tag_id']);
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
});
}
因此,它似乎与创建表的顺序或定义数据透视表的迁移无关。
感谢您帮助我理解这一点。
【问题讨论】:
标签: php laravel eloquent eloquent-relationship