Support the ongoing development of Laravel.io →
posted 10 years ago
Database
Last updated 2 years ago.
0

Also what i don't get. Why does laravel support cross-database feature when you can't make cross-database foreign keys.

Last updated 2 years ago.
0

You can. Here's how:

use Illuminate\Database\Query\Expression;

// migration class...

public function up()
{
    // rest of the migration
        
    $table->foreign('user_id')
        ->references('id')
        ->on(new Expression('database_1.users'));
}
Last updated 2 years ago.
0

For future reference if you ever change the name of the database this will not work. It is best to grab the name of the database by the database definition.

config/database.php

'auth_database' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],

Then in your migration file:

Schema::create('role_user', function (Blueprint $table) {
    $db = DB::connection('auth_database')->getDatabaseName();

    $table->integer('role_id')->unsigned();
    $table->foreign('role_id')->references('id')->on('roles');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on(new Expression($db . '.users'));
});

0

Sign in to participate in this thread!

Eventy

Your banner here too?

JeffreyR jeffreyr Joined 11 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.