Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Laravel Join mit 3 Tischen

Ich glaube, Ihr Join ist falsch:

$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('followers', 'followers.user_id', '=', 'users.id')
    ->where('followers.follower_id', '=', 3)
    ->get();

Ich schlage Ihnen auch vor, Ihre Tabelle wie folgt zu benennen:follows stattdessen fühlt es sich etwas natürlicher an zu sagen user has many followers through follows und user has many followers through follows .

Beispiel

$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('follows', 'follows.user_id', '=', 'users.id')
    ->where('follows.follower_id', '=', 3)
    ->get();

Modellansatz

Ich wusste nicht, dass Sie DB:: verwenden Abfragen und keine Modelle. Also behebe ich die Antwort und sorge für viel mehr Klarheit. Ich schlage vor, Sie verwenden Modelle, es ist viel einfacher für diejenigen, die mit dem Framework und insbesondere mit SQL beginnen.

Modellbeispiel:

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');
    }
}
class Share extends Model {
    public function user() {
        return $this->belongsTo('User');
    }
}

Beispiel für die Verwendung des Modells:

$my = User::find('my_id');

// Retrieves all shares by users that I follow
// eager loading the "owner" of the share
$shares = Share::with('user')
    ->join('follows', 'follows.user_id', '=', 'shares.user_id')
    ->where('follows.follower_id', '=', $my->id)
    ->get('shares.*'); // Notice the shares.* here

// prints the username of the person who shared something
foreach ($shares as $share) {
    echo $share->user->username;
}

// Retrieves all users I'm following
$my->followees;

// Retrieves all users that follows me
$my->followers;