Using PHP Propel ORM to perform a left join on a many-to-many relationship in MySQL

There are two tables I'm working with: one called "meeting" and the other called "attendance". The "attendance" table is a many-to-many relational database structured as follows:

Attendance:
    user_id | meeting_id | invited
    --------+------------+--------
    1       | 5          | 1
    2       | 5          | 0
    3       | 4          | 0
    3       | 5          | 1
    3       | 6          | 0

The "meeting" table has the following format:

Meetings:
    meeting_id | meeting_name | owner_id
    -----------+--------------+----------
    3          | Awesome      | 2
    4          | Boring       | 2
    5          | Cool         | 5
    9          | Sexy         | 3

In this setup, each meeting can only have one row in the table, but there can be multiple attendance rows corresponding to every possible user for each meeting.

My goal is to list all meetings where a provided userid matches either the owner_id in the "meetings" table OR where the userid is listed as attending in the "attendance" database.

For instance, when searching for userid 3, the expected result should be as follows:

Result for userid 3:
    meeting_id | meeting_name | owner_id
    -----------+--------------+----------
    5          | Cool         | 5     - Userid 3 is attending meeting 5
    9          | Sexy         | 3     - Userid 3 owns meeting 9

I've tried implementing the above logic using SQL and Propel, but my current approach results in duplicate rows per meeting due to the multiple occurrences of the meeting in the attendance database.

$criteria->addJoin(MeetingMeetingsPeer::ID, MeetingAttendancePeer::MEETING_ID, Criteria::LEFT_JOIN);

$criterion = $criteria->getNewCriterion(MeetingMeetingsPeer::OWNER_ID, Meeting::getUserId());
$criterion->addOr($criteria->getNewCriterion(MeetingAttendancePeer::USER_ID, Meeting::getUserId()));

$criteria->add($criterion); 
return $criteria;

This translates into the following SQL query:

SELECT meeting_meetings.ID, meeting_meetings.OWNER_ID, meeting_meetings.GROUP_ID, meeting_meetings.NAME, meeting_meetings.COMPLETED, meeting_meetings.LOCATION, meeting_meetings.START, meeting_meetings.LENGTH, meeting_meetings.CREATED_AT, meeting_meetings.UPDATED_AT FROM `meeting_meetings` LEFT JOIN meeting_attendance ON (meeting_meetings.ID=meeting_attendance.MEETING_ID) WHERE (meeting_meetings.OWNER_ID=1 OR meeting_attendance.USER_ID=1) 

Thank you for your assistance,

Answer №1

If you want to retrieve meetings owned by user_id 1 and those attended by user_id 1, you can execute the following SQL query:

SELECT meeting_meetings.ID, meeting_meetings.OWNER_ID, meeting_meetings.GROUP_ID, meeting_meetings.NAME, 
meeting_meetings.COMPLETED, meeting_meetings.LOCATION, meeting_meetings.START, meeting_meetings.LENGTH, 
meeting_meetings.CREATED_AT, meeting_meetings.UPDATED_AT 
FROM `meeting_meetings`
WHERE `meeting_meetings`.`owner_id` = 1
UNION DISTINCT
SELECT meeting_meetings.ID, meeting_meetings.OWNER_ID, meeting_meetings.GROUP_ID, meeting_meetings.NAME, 
meeting_meetings.COMPLETED, meeting_meetings.LOCATION, meeting_meetings.START, meeting_meetings.LENGTH, 
meeting_meetings.CREATED_AT, meeting_meetings.UPDATED_AT 
FROM `meeting_meetings`
JOIN `meeting_attendance` ON `meeting_meetings`.`meeting_id` = `meeting_attendance`.`meeting_id` AND `meeting_attendance`.`invited`
WHERE `meeting_attendance`.`user_id` = 1

This approach may seem a bit cumbersome. To improve it, you could consider adding an owner flag to the meetings_attendance table.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a PHP loop to identify the initial row of a result obtained from a MySQL query

I am trying to set a background color for the first row of each 'Dist' value in a MySQL data report that gets displayed as HTML. However, I am facing difficulty in determining which row is coming from MySQL. NO CALL First St, CO Di ...

The method save() is not defined for the stdClass object

I've been encountering a persistent issue while attempting to save data into the database. The error message that keeps appearing is: "Call to undefined method stdClass::save()". This problem stems from my controller code: $c = DB::table(&apos ...

Steps to remove a record from a database when a button is clicked using jQuery in CodeIgniter

I need help with deleting a record from the database when the delete button is clicked using JQuery in Codeigniter. Below is my code snippet. $("#project").on("click", ".dltbtn", function() { $("#cur_del").val($(this).attr("data-id")); }); $("#del_ye ...

Conceal the server's internal file structure to prevent it from being displayed in sources

When I visit my website and inspect the elements in Google Chrome, I am able to see a list of all the folders on my site under the sources tab. This reveals their original names and allows for the downloading of the entire website code. I am concerned abo ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

PHP mistakenly outputs content that is not enclosed within tags

After discovering StackOverflow, I couldn't resist sharing my PHP code conundrum with the incredible community here! So, in a WordPress template, I have this chunk of PHP: echo '<div class="thumbnail">'; echo the_post_thumbnail(); ec ...

Experiencing issues with archiving files in PHP and receiving a 'zipArchive::close() Read Error: no such file or directory in c:/' error message?

When using PHP to download multiple files as a zip folder, the code below is giving me an error message: "zipArchive::close() Read error: no such file or directory in C:// path" I have added an HTML button that, when clicked, retrieves the id of the row t ...

"Discover the trick to adding and updating text in a URL using jQuery without needing to refresh the page

I successfully implemented pagination in WordPress using Jquery/Ajax/wp_pagenavi(). It works well as it only refreshes a specific div to load new content instead of reloading the entire page. However, I am looking to enhance this feature by updating a port ...

Retrieve data from two tables in PHP and display the table name

My current PHP code is designed to retrieve data from two different tables in MySQL using the UNION statement. $sql=" SELECT 'ticket_updates' as rowTable, sequence, ticket_seq, notes as displaydata, date ...

What's the best way to set up automatic deletion on a timed schedule?

My current framework is codeigniter As an example, I have a table called A. Is it possible for my system to automatically delete all records in table A every 2 minutes? Any insights on achieving this would be greatly appreciated ...

Enable checkboxes to be pre-selected upon page loading automatically

Although I've found a lot of code snippets for a "select all" option, what I really need is more direct. I want the WpForms checkboxes to be pre-checked by default when the page loads, instead of requiring users to press a button. My goal is to have a ...

PHP array is not being successfully converted to JSON format on an online JSON editor

After printing this PHP array using print_r(), I have the following data: Array ( [title] => Atle [code] => ATL [classroom] => traditional [start_time] => 06:00 AM [end_time] => 08:00 AM [grp_day] => Array ...

Calculating the Number of Days Between Two Dates in PHP

Here is the code snippet I am working with: $dateStart = get_post_meta( get_the_ID(), 'startdate' , true); $dateStart = DateTime::createFromFormat('d/m/Y h:i:s', $dateStart); $dStart = $dateStart->format('d/m/y');true); $d ...

What is the best method to store the name of an image as a session variable?

<!--images acting as buttons--> <form> <img src="peanuts.jpg"" class="qac left" onclick="qac_search()" name="Peanuts"> <img src="milk.jpg" class="qac" onclick=&qu ...

dispatch email display Twitter Bootstrap notification utilizing Ajax

I'm trying to set up an email sending feature via a contact form. I want it to send the email and display a Bootstrap alert confirming that the email has been sent. Below is the HTML code: https://jsfiddle.net/6rfeas35/. Additionally, here is my PHP c ...

Integrate a PHP form that includes a redirect feature and an optional opt-in box

I'm a beginner and I'm trying to enhance this code by adding some extra features. When the form is submitted, I want the page to redirect to an external URL like www.google.com The checkbox should be automatically checked and when the client re ...

Unable to process JavaScript function

Still in the process of developing my "mvc/social" PHP project, I am currently focusing on securing user input for the status message. I have created both a PHP and JavaScript function for this purpose, but it seems like the JavaScript function is not bein ...

Verifying Emails using CRUD API in Laravel 9

I have a question about email verification using Laravel. There are specific server considerations: The client consumes an API that only needs to return JSON responses, not views via HTTP. Therefore, all routes are defined in api.php instead of web.php. ...

Learn how to make an Ajax request in Laravel 5 using XAMPP server

routes.php Route::get('/login',function(){ $data = 'Login'; return View::make('user.login'); }); Route::post('/login',function(){ $formData = Input::get('userData'); parse_str($formData, $ ...

Exploring the Depths of Laravel Eloquent: A Guide to Master

Seeking guidance as a beginner in Laravel, I have encountered an issue with laravel relationships. Could use some assistance from the experts here. Dealing with four tables: 1. Users 2. Teams 3. Games 4. Picks The Picks table serves as my interme ...