Laravel Nova BelongsToMany relation | models in two separate databases

37 Views Asked by At
  • Laravel Version: 10.47.0
  • Nova Version: 4.23.0 (Silver Surfer)
  • PHP Version: 8.2.13
  • Database Driver & Version: MySQL 10.11.6-MariaDB-1:10.11.6+maria~deb11
  • Operating System and Version: Debian 11
  • Browser type and version: Chrome 122.0.6261.95
  • Reproduction Repository: -

Description:

I have many to many relation where Products are stored in another database than Distribution. I tried few solutions but none seems working. I searched nova changelog to see if there was fixes for it and it seems that there were none. Nova keep search for distribution_product table in "corcel" connection. I want store distribution_product table in "mysql" connection.

I'm doing something wrong or it is a bug?

Distribution model:

protected $connection = 'mysql';
public function product(): BelongsToMany
    {
        return $this->belongsToMany(Product::class)->withPivot('amount')->using(DistributionProduct::class);
    }

DistributionProduct model:

class DistributionProduct extends Pivot
{
    protected $connection = 'mysql';

    protected $table = 'distribution_product';
}

Product model:

class Product extends model
{

    protected $connection = 'corcel';

    public function distribution(): BelongsToMany
    {
        return $this->belongsToMany(Distribution::class)->withPivot('amount')->using(DistributionProduct::class);
    }
}

Detailed steps to reproduce the issue on a fresh Nova installation:

php artisan make:model -m Distribution
php artisan make:model -m Product
php artisan make:model -m DistributionProduct --pivot
php artisan nova:resource Distribution
php artisan nova:resource Product
php artisan migrate

add corcel mysql connection to config/database.php

updade models like in description 

Error:

 "message": "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'corcel_database.distribution_product' doesn't exist (Connection: corcel, SQL: select `posts`.*, `distribution_product`.`distribution_id` as `pivot_distribution_id`, `distribution_product`.`product_ID` as `pivot_product_ID`, `distribution_product`.`amount` as `pivot_amount` from `posts` inner join `distribution_product` on `posts`.`ID` = `distribution_product`.`product_ID` where `post_type` = product and `distribution_product`.`distribution_id` = 2)",
    "exception": "Illuminate\\Database\\QueryException",
    "file": "/vendor/laravel/framework/src/Illuminate/Database/Connection.php",
0

There are 0 best solutions below