Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ozmnow's avatar

Select from two tables and join result on a third table

I wonder if its possible to select two tables and join a third table

I have 3 tables:

upvotes -id (PK) -voteOn (FK) - points to users PK -voteBy (FK) - points to users PK -vote (Int) -voteAdded (Int) - unix timestamp

downvotes -id (PK) -voteOn (FK) - points to users PK -voteBy (FK) - points to users PK -vote (tinyInteger) -voteAdded (Int) - unix timestamp

users id (PK) username

What I now want to do is ~ select ALL votes from the tables upvotes and downvotes where voteOn = 2 then join table users on voteBy orderBy voteAdded Asc

More or less I want to get all votes on a specific user then join the users table so that I can get the username of the person who placed the vote

0 likes
1 reply
bitcoinboy's avatar

Hi this will be made easily using Eloquent relations:

create upvote, downvote models using Artisan:

php artisan make:model upvote

php artisan make:model downvote

//Add this to app/User.php

    //User Upvotes relation
    public function upvotes()
    {
        return $this->hasMany(Upvote::class);
    }

   //User Downvotes relation
    public function downvotes()
    {
        return $this->hasMany(Upvote::class);
    }

//Add this to your script

        $user = User::with(['upvotes' => function($query){
            $query->where('upvotes.voteOn', 2);
            $query->orderBy('upvotes.created_at');
        }, 'downvotes' => function($query){
            $query->where('downvotes.voteOn', 2);
            $query->orderBy('downvotes.created_at');
        }])->orderBy('created_at')->get();

1 like

Please or to participate in this conversation.