I'm a new to the OOP programming . But I think I understand what is an ORM: in practice, the ORM libraries allow to abstract the database in an object and handle it as if it were a class in OOP programming.
Am I correct? Eloquent is the library that manages ORM in Laravel and to use that it's necessary extend the model (the business logic of a software in MVC architecture)
tl;dr: ORMs manage the conversion of simple integer-based relationships in the database to instances of classes that you can work with in your code.
You're confused in a couple different areas.
First, and quickly, MVC is one layer of an application; specifically it is part of the presentation layer. Your business logic should be completely independent of the MVC layer.
RDBMSs like MySQL and PostgreSQL are inherently bad at establishing and maintaining the various relationships that fundamental to object oriented programming. In the classic blog example, your Post
belongs to a User
, and the user might have several posts. If we tried to just recursively serialize these objects and store them, we would end up with a lot of circular (and hence infinite) loops.
Instead, we use a system of indices and keys to make a permanent note in the database about some other related object. These might reference a table, but are no representation of the concrete relationship that will be established programmatically.
So then we have the ORM. The ORM knows, via foreign keys and relationship methods in Eloquent, that the user_id column on a row in the posts table actually correlated to a User object. This happens under the hood once you add the relationship (see below) so that you can reference this user at any time, as long as the user exists, without having to work with the database or even be aware that the underlying data isn't already an object.
We might see the following in Post.php
:
public function user() {
return $this->belongsTo(User::class);
}
If we have a user_id of 5, Eloquent uses a little grammatical magic (specifically, lower-snake cases the class and appends _id) to find the user with the id of 5. When you retrieve this, either via eager loading or lazy loading, eloquent will then use the retrieved data to hydrate a User
object.
The abstraction lies in the fact that technically the class/object has no knowledge of the database structure, Eloquent instead handles the conversion to and from property names and column names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With