【问题标题】:Many to many relationship in Voyager Admin PanelVoyager 管理面板中的多对多关系
【发布时间】:2017-05-17 17:41:34
【问题描述】:

当我尝试使用 voyager 的 BREAD 创建器添加具有多对多关系的新项目时出现此错误:

SQLSTATE[23000]:违反完整性约束:1052 列 'id' 在 字段列表不明确(SQL:select id from products inner join order_product on products.id = order_product.product_id 其中order_product.order_id 为空)(查看: D:\WindowsFolders\Documents\PHP\Voyager-test\vendor\tcg\voyager\resources\views\bread\edit-add.blade.php)

我已按照文档进行操作,但不确定问题出在哪里。对我来说,我的多对多设置看起来应该在普通的 Laravel 中工作,但是当我尝试在 voyager 面板中添加一个新的 order 项目时它会抛出该错误。而且文档确实没有指定父表中的额外字段应该是什么(我在其中发表评论)。

这是我的orderorder-pivot 表;

public function up()
{
    Schema::create('orders', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->text('comment')->nullable();
        $table->integer('price');
        $table->boolean('sent');
        $table->boolean('paid');
        $table->string('products'); // This thing
        $table->timestamps();
    });

    Schema::create('order_product', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('order_id')->unsigned();
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
        $table->integer('product_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products');
        $table->integer('amount');
        $table->timestamps();
    });
}

这是产品表:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title')->nullable();
        $table->text('description');
        $table->string('image');
        $table->integer('price');
        $table->string('slug')->unique();
        $table->timestamps();
    });
}

这里是关系函数:

public function products()
{
    return $this->belongsToMany(Product::class, 'order_product');
}

最后一张来自Order BREAD 部分的图片:

【问题讨论】:

    标签: mysql laravel


    【解决方案1】:

    在这种情况下,MySQL 错误消息非常清楚:productsorder_product 表都有 id 字段。问题中sql语句的select列表只有id,因此MySQL无法决定id字段应该从哪个表中选择。

    需要在字段名前加上表名才能清楚:

    select products.id from ... 
    

    【讨论】:

    • 换句话说,问题在于应该选择和连接字段的内容和方式的代码,而不是表本身?
    • 没错。虽然,从技术上讲,您可以从 order_product 表中删除 id 字段,并将 order_id - product_id 字段的组合作为主键(无论如何,您都缺少这两个字段的唯一约束)。
    • 只是尝试一下,我该怎么做呢? MySQL/eloquent 对我来说仍然是最陌生的编程。你是说复合键吗?
    • 是的,复合或多列键是您所需要的。 laravel.com/docs/5.0/schema#adding-indexes
    【解决方案2】:

    我遇到了类似的问题,并通过在 Voyager Admin 的 json 选项中将关系键从 id 更改为 product_id 解决了这个问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      相关资源
      最近更新 更多