Home >Database >Mysql Tutorial >How to Join Three Tables in Laravel for a Twitter-like Feed?
Laravel Join with 3 Tables
To join three tables in Laravel for a Twitter-like feed, the join query can be constructed as follows:
$shares = DB::table('shares') ->join('users', 'users.id', '=', 'shares.user_id') ->join('followers', 'followers.user_id', '=', 'users.id') ->where('followers.follower_id', '=', 3) ->get();
This query joins the shares, users, and followers tables based on the conditions specified in the join clauses.
Another approach is to use models instead of raw queries for a more object-oriented approach. Here is an example using models:
// Define User Model class User extends Model { public function shares() { return $this->hasMany('Share'); } public function followers() { return $this->belongsToMany('User', 'follows', 'user_id', 'follower_id'); } public function followees() { return $this->belongsToMany('User', 'follows', 'follower_id', 'user_id'); } } // Define Share Model class Share extends Model { public function user() { return $this->belongsTo('User'); } } // Model Usage $my = User::find('my_id'); $shares = Share::with('user') ->join('follows', 'follows.user_id', '=', 'shares.user_id') ->where('follows.follower_id', '=', $my->id) ->get('shares.*'); foreach ($shares as $share) { echo $share->user->username; }
By using this model approach, you can retrieve all shares from users that the logged-in user follows, eagerly loading the user who created the share.
The above is the detailed content of How to Join Three Tables in Laravel for a Twitter-like Feed?. For more information, please follow other related articles on the PHP Chinese website!