laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

Related instance not being created with newRelatedInstance method

Open michaeljennings opened this issue 2 years ago • 0 comments

  • Laravel-mongodb Version: 3.8.4
  • PHP Version: 7.4.16
  • Database Driver & Version: php extension, version 4.4

Description:

I have an application where I have two mongo databases on two different laravel db connections. One of the mongo connections is the default laravel connection, the other one I specify when I need to connect to it.

In laravel when you load a relationship it hits the newRelatedInstance model, if the related model doesn't have a connection specified it will set the db connection on the related model to the same as the main model. For example if I have a user model that specifies a 'foo' connection and I lazy load the user's role and that role model doesn't have a connection specified, it will set the role connection to 'foo'.

The problem I'm having is in the HybridRelations trait it isn't calling the newRelatedInstance method, it just creates a new model by doing new $related. This is causing laravel to hit the wrong database connection and then not find a #result.

In this specific app I can't set the connection property on the related model as some models are saved in the main database, and then copied over to the other database at a later stage.

I think we could also use this as a chance to fix #2223, as we could update the newRelatedInstance to only keep on the same connection if the model is a mongodb model. If it is a default eloquent model and it doesn't have a connection specified it could fall back to the default.

I'm happy to add a merge request showing how this would work.

Steps to reproduce

  1. Create a new laravel app
  2. Add two mongo db connections; mongo1 and mongo2
  3. Set mongo1 as the default database connection
  4. Create a model and a relational model with a belongs to relationship
  5. On the main model set the connection property to mongo2
  6. Add values into the mongo 2 connection for the main model and the relational model
  7. Find the main model and try to access the relationship and it will return null

Expected behaviour

I'd expect if you load a relationship from a model and the related model doesn't have a connection specified, then it should attempt to load it from the same connection as the parent model. I would however expect if the related model wasn't a mongodb model that it should load from the default connection.

Actual behaviour

If a connection isn't specified it loads the relationship from the default database connection.

michaeljennings avatar Nov 24 '21 15:11 michaeljennings