Question:
Before I start, I am using Laravel 8 & PHP 7.4.29.The effect I want to achieve is that you can get the username from another table (of users) based on column from the first table (of videos).
Let’s take a closer look on the first table. It contains such columns as
title
, description
, uploader
(having a value of UUID of the user), etc. The problem I am facing is that I am actually unable to retrieve the username I want. Instead of, I am getting such error:(the code is written properly, but Stack Overflow syntax highlighting is broken, I guess)
I’ve browsing Stack Overflow a while ago and found the solution, that I should retrieve data from both tables in one SQL request (in my case –
select * from videos, users
). It somehow worked, but instead of expected result (I have 1 video information in the first table & 2 users in the second table), the results were duplicated.I actually had some experience with PHP and Laravel back then, but I can’t recall how could this be done (I’ve took a fairly big break from programming in PHP). If there’s any solution, it would be welcome.
Thanks in advance!
Answer:
Use Joinsin your case, Use left join if you have videos without matching uploader and if you need all the videos.
also you can use inner join if you want to get videos only if the matching uploader exists in the table.
Note : If you have a common column in both tables then the value of the videos record will be overrided by users column value
Ex : videos [id,name,uploader,addedAt] users [uuid, name]
(Example only)
If you have better answer, please add a comment about this, thank you!