Question

I am trying to select rows and add to this selection a boolean to test the existence of a many-to-many relationship recorded in an other table.

Here is my code :

$q = $this->dao->prepare('
        SELECT wishlists.id, wishlists.title, wishlists.comment, wishlists.date, users.name, users.username
        FROM wishlists
            LEFT JOIN users ON wishlists.user = users.id
            WHERE users.username = :username
        ORDER BY wishlists.date DESC
        ');

    $q->bindValue(':username', $user);

    $q->execute();

This will return a table with all my fields. I would like to add a column to this table with this kind of subquery :

SELECT EXISTS(SELECT 1 FROM wishlists_following WHERE wishlist_id = wishlists.id AND user_id = :current_user_id)

Where current_user_id is the id of the visitor and $user is the current user profile page.

What is the best way to do that?

The goal is to get all informations about a wishlist AND to know if current user is following this wishlist (in order to display a following button or not for each wishlist returned).

Was it helpful?

Solution

as you use a LEFT JOIN between wishlist and users, if there is no related user to a wishlist, you will get a NULL value for columns username and user.

So I don't think you need another query : you just have to test the nulliness of column users.name once you get the results of your first query.

OTHER TIPS

Check the name or username fields in your first query - either in query directly or in your script after executing the query, if it is null it means user is not following the wishlist, otherwise s/he does. Key thing is using LEFT join allowing this and you already have it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top