From Joomla! Documentation
< User:MarkRS | misc
The Database Object
In Joomla 4 using the database access object has changed somewhat. The old method ("Factory::getDbo()") still works but complains that it's deprecated, without referring to a better method. As if that isn't bad enough, large chunks of the Joomla core still use this strategy! So, what to do? Here's some answers.
In putting this piece together I am indebted to the discussion in the github repository at https://github.com/joomla/joomla-cms/discussions/38111 .
In the Model
In the model class this is particularly easy, as you might expect.
As long as you're inheriting from core Joomla models that access the database you can simply write
which works as long as you inherit, either directly or indirectly, from BaseDatabaseModel. Looking at the models that inherit from this, even just directly is quite instructive and will show many features that you didn't know were accessible (or existed), however the models you're probably most likely to need are FormModel, AdminModel, ItemMode, ListModel.
It is easy to imagine that the base data models have code to access the database, but that's just what it would be, imagining. In fact they access the database through the DatabaseAwareTrait and it is this which actually contains the reference to the database object. This works for models because models are loaded by the MVCFactory, and it is this which loads the DatabaseAwareTrait with the database reference.
So, "use"ing this trait in a class will give you access to the database functionality, even if your model doesn't inherit from BaseDatabaseModel.
Outside a Model
Of course, using the Joomla version of MVC the only place to access the data layer is in model code, isn't it? Well actually no, that's not the only valid place. A very valid other place, for example, is when defining a field, or just as validly a helper! You might say that doing this should load the model to access the data, which is also quite a valid argument, but again not one that's been rigorously applied in the Joomla core so you could be forgiven for not applying it yourself.
Even if you're not writing component code, you can access the database the same way the MVCFactory does, with
This will work because, whatever code you're writing, it will be executed within a component. The container that is "got" here is the component container, so you're all good.