为什么用 hasManyThrough 调用相关数据会出错?

问题描述 投票:0回答:1

在 laravel 10 应用程序中,我有 3 个相关表:

    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('title', 255);
    ...

    Schema::create('discounts', function (Blueprint $table) {
        $table->tinyIncrements('id')->unsigned();
        $table->string('name',100)->unique();
    ...

    Schema::create('discount_product', function (Blueprint $table) {
        $table->id();
        $table->foreignId('product_id')->references('id')->on('products')->onDelete('CASCADE');
        $table->unsignedTinyInteger('discount_id')->unsigned();
        $table->foreign('discount_id')->references('id')->on('discounts')->onUpdate('RESTRICT')->onDelete('CASCADE');
    ...

从折扣编辑器中,我尝试将相关产品与产品一起加载,但出现错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.discount_id' in 'on clause' (Connection: mysql, SQL: select `products`.*, `discount_product`.`product_id` as `laravel_through_key` from `products` inner join `discount_product` on `discount_product`.`id` = `products`.`discount_id` where `discount_product`.`product_id` = 2 order by `products`.`id` desc limit 6 offset 0) {"userId":1,"exception":"[object] (Illuminate\\Database\\QueryException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.discount_id' in 'on clause' (Connection: mysql, SQL: select `products`.*, `discount_product`.`product_id` as `laravel_through_key` from `products` inner join `discount_product` on `discount_product`.`id` = `products`.`discount_id` where `discount_product`.`product_id` = 2 order by `products`.`id` desc limit 6 offset 0)

在折扣模型中,我定义了一个关系:

public function products() {
    return $this->hasManyThrough(
        Product::class,
        DiscountProduct::class,
        'product_id', // Foreign key on the products table...
        'discount_id', // Foreign key on the discounts table...
        'id', // Local key on the discounts table...
        'id' // Local key on the products table...
    );
}

Look like the relation above is invalid... Which syntax is valid ?
laravel eloquent
1个回答
0
投票

看起来您正在尝试通过数据透视表

products
discounts
模型加载相关的
discount_product
。发生错误的原因是
hasManyThrough
关系不适合多对多关系。在您的情况下,由于产品和折扣是通过数据透视表链接的,因此您应该使用
belongsToMany
关系而不是
hasManyThrough

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

belongsToMany
的参数是:

  • Product::class
    – 相关模型。
  • discount_product
    – 数据透视表的名称。
  • discount_id
    discount_product
    表上引用
    discounts
    表的外键。
  • product_id
    discount_product
    表上引用
    products
    表的外键。
© www.soinside.com 2019 - 2024. All rights reserved.