0

I need to make the relationship between two connections. A user can have many different clients and databases.

class User extends Authenticatable
{
    protected $connection = 'mysql';
}
class Client extends Model
{
    protected $connection = 'sqlsrv';
}

I created a ClientUser helper table with two columns user_id and client_id, client_type.

In User Model I created the method:

public function clients()
{
    return $this->hasMany(ClientUser::class);

}

And in ClientUser Model created the method:

public function client()
{
    return $this->morphTo('client');
}

But every time I want to access the clients of a particular user I have to call Model ClientUser first and then Model Client: Exp.:

$user = \App\User::find(1);
$clientUser = $user->clients()->get();
foreach ($clientUser as $item) {
    echo $item->client()->first()->Name;
}

I would like to know if there is any way to access Model Client directly from Model User?

MSilva
  • 1
  • Check this out, I think you gonna find your answer here – Tohid Dadashnezhad Aug 22 '19 at 18:24
  • https://stackoverflow.com/questions/32422593/laravel-belongsto-relationship-with-different-databases-not-working – Tohid Dadashnezhad Aug 22 '19 at 18:24
  • @TohidDadashnezhad In this case the connections are different but in the same bank, the only difference is the schema. In my case one connection is on mysql and another on sqlsrv – MSilva Aug 22 '19 at 18:46
  • With the code you posted I don't understand the `morphTo('client');` in `ClientUser` Model, can you add more details please? And on what connection is `ClientUser`? – dparoli Aug 22 '19 at 19:22
  • @dparoli I used morphto because I was trying other solutions, but the result would be the same if using hasmany. ``` public function client() { return $this->hasMany(Client::class,'client_Id', 'Id'); } ``` The Model ClientUser table is an intermediate table for making the One to Many relationship. – MSilva Aug 23 '19 at 11:41
  • A User (mysql) Has Many Clients (sqlsrv). What I want from Model User (mysql) is to directly access Model Client, Model UserClient becomes invisible. – MSilva Aug 23 '19 at 11:41

0 Answers0