Replies: 2 comments 3 replies
-
Hi. From what I know the relations (by default) are considered to be in the same connection. So for me this is expected behavior. |
Beta Was this translation helpful? Give feedback.
-
I would say it depends on the use case. For example, in my case, I had many models (all using the default connection). Then I needed to add a model with a new connection, and, in that model to have a relation with another (already created, with default connection) model. So, my expected behavior was that the model I was already using with the default connection would keep using the same connection it was previously using. But, either way, I think it would be nice to have a way to explicitly specify the desired behavior to use in a model. I think it could be a static property to be able to set it for all models as well. Something like:
<?php
namespace Illuminate\Database\Eloquent;
abstract class Model
{
// ...
protected static $modelShouldInheritConnection = false;
// ...
public static function inheritsConnection(): bool
{
return static::$modelShouldInheritConnection;
}
public static function shouldInheritsConnection(bool $value = true): void
{
static::$modelShouldInheritConnection = $value;
}
// ...
} Then we could be able to set in the Model::shouldInheritsConnection(true); And also be able to change the behavior in a specific model like: <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Child extends Model
{
protected static $modelShouldInheritConnection = false;
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Laravel Version
11.19.0
PHP Version
8.3.8
Database Driver & Version
MySQL 5.7.44
Description
Having a model, without
$connection
property specified, as a relation from another model with explicit$connection
causes the child to use the parent's connection instead of the default connection.I found out this behavior was implemented in #16103 but I think it might not be the desired behavior.
According with what the documentation says, it should use the default connection (and that was exactly what I was expecting):
Steps To Reproduce
Child Model:
Parent Model:
Proposed solution:
I think it could be implemented something like this:
Model.php
HasRelationships.php
Then in the model you want to inherit the parent's connection:
Or it could be set to
true
by default so as not to break the current behavior.Kind regards!
Beta Was this translation helpful? Give feedback.
All reactions