Question on Object Relation Mapper(ORM) doining the work of Relational Database(join)

@TomB After reading through your book(PHP mysql 6th edition which you co-authored with teacher Kevin Yank). You talked about using ORM instead of using JOIN. In the book, all the examples are based on 2 tables. How can I use ORM to join 3 tables and above.This is a rough sketch. Relational Database, you do this in joining 3 tables together.

SELECT user.id, name, email.id, mail.user_id, email, sport, sport.user_id FROM user LEFT JOIN mail ON email.user_id = user.id LEFT JOIN sport.user_id = user.id`

This is shown in the book, but each table has its own entity class.

I’m not sure why you’re joining mail to sport so I’ll use an online shop as example. Each order has a user, and set of products

$order = $ordersTable->findById(123);

echo 'Order No. ' . $order->id;
echo 'Order date. ' . $order->date;

echo 'Shipping address';
echo $order->getUser()->getShippingAddress()->address1;
echo $order->getUser()->getShippingAddress()->address2;


foreach ($order->getItems() as $orderItem) {
	
	echo $orderItem->getProduct()->name;
	echo $orderItem->getProduct->getManufacturer()->name;
	echo $orderItem->quantity;
	echo $orderItem->price;
}

Each function queries the next table in the chain. Express your relationships in the table’s entity class.

Thanks for the quick response sir. But there will be places sir where ORM will be useless to use. How can we then know that

I’m afraid I’m not sure what you mean, can you rephrase the question?

To understand sir, I would like to share a query from the creator of Hibernate

Just because you’re using Hibernate, doesn’t mean you have to use it for everything…

There will be cases where it wont be the best decision to use ORM

As with everything it depends on a lot of factors, however an ORM will reduce the need to repeatedly write code to write queries. It also allows you to decouple your application from the database, the ORM could be using a CSV or JSON file behind the scenes instead of a database.

If you’re using an ORM in a project, you’re probably better off being consistent and using it throughout. If you are building on top of an existing project which has queries everywhere, you’re probably better off not introducing an ORM (or the next person to look at the code will be frustrated).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.