Relationship ORM, PHP and SQL Join

I am working on a small PHP Framework for a school project, and now I'm learning how to create an ORM part.

However, I cannot figure out how to correlate the relationship of objects with a SQL query with joins, or I just don’t know the right words to search for :(

t1 id title text 

-

 t2 id name description 

I tried to make it simple: SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.t1_id

What I get is a simple array with all fields from both tables, and the id column is overridden because it exists in both.

 [ "id" => "2" "title" => "Lorem" "text" => "Ipsum" "name" => "Tomato" "description" => "Tomato are nice" ] 

So my question is: is there an easy way to get something like this using connections?

 [ "t1" => [ "id" => 2 "title" => "Lorem" "text" => "Tomato" "t2" => [ "id" => 3 "name" => "Tomato" "description" => "Tomato are nice" ] ] 
+4
source share
1 answer

No, the join is for creating a tabular view of two tables on the side. But you can do:

 SELECT t1.id, t1.title, t1.next, t2.name as "t2_name", t2.description as "t2_description" FROM t1 LEFT JOIN t2 ON t1.id = t2.t1_id 

Which will give you prefixes like:

 [ "t1" => [ "id" => 2 "title" => "Lorem" "text" => "Tomato" "id" => 3 "t2_name" => "Tomato" "t2_description" => "Tomato are nice" ] ] 

This solves the same problem you were trying to solve.

+1
source

All Articles