Yassin
Yassin

Reputation: 21

Many-To-Many Relationship not working across databases (Laravel 5.2)

I'm trying to develop a new laravel 5.2 app using two databases/connections Specified my default connection in app/config/database

 'default' => 'connection-one',

A normal one-to-one relation across two databases is working as expected.

but the problems starts when a use many to many relationship

lets say i have two models Post and Category

a post has many categories and a category belongs to many posts

Post model :

class Post extends Model
{
   public function categories()
   {
      return $this->belongsToMany('App/Category');
   }    
}

Category model

class Category extends Model
 {
   public function posts()
   {
      return $this->belongsToMany('App/Post');
   }    
}

Model intermediate:

class CategoryPost extends Model
 {
   protected $connection = 'connection-two';
   protected $table = 'category_post_table';    
}

now in the migration, laravel create three tables ( posts , categories and category_post)

the idea is to make posts and categories tables in the first database ( default connection ) and make the category_post table in the second database.

laravel created this tables in their places but when i want to retrieve data with eloquent, laravel assume that the table category_post existing in the first database and show error whene he 's not found the table.

How do I make laravel search in table category_post in the second database.

Upvotes: 0

Views: 82

Answers (1)

Zulfiqar Tariq
Zulfiqar Tariq

Reputation: 394

laravel relations are not supported across multiple databases. The reason is that laravel relation are translated into sql queries.

Upvotes: 0

Related Questions