문제

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).

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top