Ad

Composite Foreign Key In Laravel

- 1 answer

How do I write this constrain in a Laravel migration?

ALTER TABLE user_profiles 
   ADD CONSTRAINT app_profiles 
       FOREIGN KEY (profile_id, app_id) 
       REFERENCES profile_apps (profile_id, app_id);

I've tried this:

$table->foreign(['profile_id', 'app_id'])->references('profile_apps')->on(['profile_id', 'app_id']);

which turns into:

"ErrorException : Array to string conversion" in C:\Users\CAM\Projects\mcr-back\vendor\laravel\framework\src\Illuminate\Database\Grammar.php:39

and the same as strings,

$table->foreign('profile_id, app_id')->references('profile_apps')->on('profile_id, app_id');

with error:

"SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'profile_id, app_id' doesn't exist in table"

Ad

Answer

You are mix up on and references methods using.

Right variant is:

$table
    ->foreign(['profile_id', 'app_id'])
    ->references(['profile_id', 'app_id'])
    ->on('profile_apps');
Ad
source: stackoverflow.com
Ad