我有两个模型,他们都没有使用表中的ID,但字段internal_id.所以我定制了我的枢轴架构,但我一直坚持连接它们.我得到错误:
General error: 1215 Cannot add foreign key constraint (sql: alter table `SEOshop_category_product` add constraint SEOshop_category_product_category_id_foreign foreign key (`category_id`) references `SEOshop_categories` (`internal_id`) on delete cascade)
迁移的代码是:
Schema::create('SEOshop_category_product',function(Blueprint $table) { $table->increments('id'); $table->integer('category_id')->unsigned()->index(); $table->foreign('category_id')->references('internal_id')->on('SEOshop_categories')->onDelete('cascade'); $table->integer('product_id')->unsigned()->index(); $table->foreign('product_id')->references('internal_id')->on('SEOshop_products')->onDelete('cascade'); $table->timestamps(); });
作为SEOshop_categories.internal_id的SEOshop_products.internal_id这两个字段都是现有的,列类型都是int(11).
谁能告诉我出了什么问题?
表SEOshop_categories和SEOshop_products的迁移
//SEOshop_products public function up() { Schema::create('SEOshop_products',function(Blueprint $table) { $table->increments('id'); $table->integer('shop_id'); $table->integer('internal_id')->signed()->index(); $table->integer('internal_variant_id'); $table->string('visible'); $table->string('tags'); $table->timestamps(); }); } //Table SEOshop_categories public function up() { Schema::create('SEOshop_categories',function(Blueprint $table) { $table->increments('id'); $table->integer('internal_id')->signed()->index(); $table->datetime('SEOshop_created_at'); $table->datetime('SEOshop_updated_at'); $table->text('full_description'); $table->timestamps(); }); }
好的,所以现在我已经创建了我的表,它的工作原理应该如何.我需要让我的产品有类别(多2个).所以我用
SEOshopProduct::find(1)->with('categories')->get();
[8] array(3) { ["query"] "select `SEOshop_categories`.*,`SEOshop_category_product`.`product_id` as `pivot_product_id`,`SEOshop_category_product`.`category_id` as `pivot_category_id` from `SEOshop_categories` inner join `SEOshop_category_product` on `SEOshop_categories`.`id` = `SEOshop_category_product`.`category_id` where `SEOshop_category_product`.`product_id` in (?)" ["bindings"] array(1) { [0] 8 } ["time"] 0.37 }
产品和类别的internal_id大于10.000,我在查询中看不到它.
我的模特:
产品:
public function categories(){ return $this->belongsToMany('SEOshopCategory','SEOshop_category_product','product_id','category_id'); }
分类:
public function products(){ return $this->belongsToMany('SEOshopCategory','category_id','product_id'); }