calin.ionut's avatar

how to use composite foreign key (hasMany)

I have this tables:

Schema::create('variants', function (Blueprint $table) {
            $table->unsignedBigInteger('VariantID');

            $table->unsignedBigInteger('ProductID');
            $table->foreign('ProductID')->references('ProductID')->on('products');

            $table->string('SKU')->unique();
            $table->decimal('Price',10,2);
            $table->integer('Stock');

            $table->primary(['VariantID', 'ProductID']);

            $table->timestamps();
        });
Schema::create('variant_values', function (Blueprint $table) {
            $table->unsignedBigInteger('ProductID');
            $table->unsignedBigInteger('VariantID');
            $table->unsignedBigInteger('OptionID');
            $table->unsignedBigInteger('OptionValueID');

            $table->foreign('ProductID')->references('ProductID')->on('variants');
            $table->foreign('VariantID')->references('VariantID')->on('variants');

            $table->primary(['ProductID', 'VariantID', 'OptionID']);
        });

The Variant.php model

protected $table = 'variants';

    protected $primaryKey = ['VariantID', 'ProductID'];
    public $incrementing = false;

    public function variantValues(){
        return $this->hasMany(VariantValue::class, '[VariantID, ProductID]');
    }

and the Variantvalue.php model

 protected $table = 'variant_values';

    protected $primaryKey = ['ProductID', 'VariantID', 'OptionID'];
    public $incrementing = false;

    public $timestamps = false;

The problem is in the model Variant.php

  public function variantValues(){
        return $this->hasMany(VariantValue::class, '[VariantID, ProductID]');
    }

when use on a variant to see the values.

It complains:

array_key_exists(): The first argument should be either a string or an integer

It is possible to use the relation hasMany with composite foreign key in laravel 6 ?

0 likes
2 replies
calin.ionut's avatar

I have changed to this and seems to work.

public function variantValues(){
        return
            $this->hasMany(VariantValue::class, 'VariantID','VariantID')
                     ->where('ProductID','=',$this->ProductID);
    }
Čamo's avatar

@calin.ionut This should not work cause where clause is not evaluated as a part of relation.

Please or to participate in this conversation.