Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel relationship DB connection

I m trying to get Model relationship with different connection, basically my connections are dynamic.

$con = 'con1'
$persons = new \App\Models\Person;
$persons->setConnection($con);
$persons = $persons->where('somevalue', 1)->get()

So here I get Person from con1 (where con1 is stored in config/databse.php It can be con2, con3, con4 and etc.

However this works, but when I am trying to loop through this data and get relationship it switches to default Database connection.

@foreach($persons as $person)
   {{$person->data->name}}
@endforeach

In above loop data is a belongsTo relation ship in Person Model, and it throws error because it switches back to default Database connection and not using con1

It is possible to setConnection() and keep for hasMany relationship and also for belongsTo relationship?

I cant set protected $connection; in Model because connections are changble

What I tried until now is I created an absctract class that extendseloquent, and my models extending this abstract class

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Eloquent;

abstract class Database extends Eloquent {
    protected $connection;
}
<?php

namespace App\Models;
use App\Models\Database as Database;
class Person extends Database{
    protected $table = 'persons';
}

So theoritically when I setConnection I set connection to all models that extends this class but still no luck.

like image 597
Froxz Avatar asked Feb 02 '26 12:02

Froxz


1 Answers

You may try eager loading of the relationship:

$persons = $persons->with('data')->where('somevalue', 1)->get();
like image 181
The Alpha Avatar answered Feb 04 '26 01:02

The Alpha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!