복붙노트

[SQL] 3 개 테이블과 조인 Laravel

SQL

3 개 테이블과 조인 Laravel

나는 트위터와 같은 응용 프로그램을 구축하고있다. 난 단지 내가 따라 사용자의 게시물을 표시하려는 피드가있다.

조인과 나는 모든 것을 시도했지만 아무것도 작동하는 것 같다 없습니다.

사용자, 팔로워, 주식 : 나는 3 개 테이블이

표는 다음과 같다 :

사용자 : ID

팔로워 : USER_ID, follower_id

주식 : USER_ID

내가하는 데 필요한 것은 "모든 공유 WHERE share.user_id = followers.follower_id"입니다 "ANDWHERE followers.user_id = users.id"

가정의 users.id가 3,이 시도 :

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

그러나 그것은 작품을 나던.

어떤 도움에 감사드립니다 :)

해결법

  1. ==============================

    1.나는 당신이 잘못 가입 믿는다

    나는 당신이 잘못 가입 믿는다

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

    나는 또한 다음 사용자가 다음을 통해 많은 관심 회원을 가지고 통해 사용자가 많은 추종자가 말을 좀 더 자연스러운 느낌 대신 다음과 같이 테이블의 이름을 지정하는 것이 좋습니다.

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

    난 당신이 모델 DB :: 쿼리를 사용하지 않은 몰랐어요. 내가 대답을 고정하고 많이 더 선명도를 제공하고 있습니다 그래서. 나는 특별히 프레임 워크와 SQL과 그 시작에 훨씬 쉽게, 당신이 모델을 사용하는 것이 좋습니다.

    모델의 예 :

    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');
        }
    }
    

    모델 사용의 예 :

    $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;
    
  2. ==============================

    2.일반적으로 MySQL의 구문의 측면에서,이 최고 기록 :

    일반적으로 MySQL의 구문의 측면에서,이 최고 기록 :

    SELECT * FROM USER a JOIN FOLLOWERS b ON (a.id = b.user_id) JOIN SHARES c on (b.follower_id = c.user_id) WHERE a.id = 3
    

    모든 추종자와 해당 주식의 데이터 세트를 반환합니다.

    난 당신이 Laravel에 다음을 원하는 것이 생각

    DB::table('USER')
      ->join('FOLLOWERS', 'USER.id', '=', 'FOLLOWERS.user_id')
      ->join('SHARES', 'FOLLOWERS.follower_id', '=', 'SHARES.user_id')
      ->where('USER.id', 3)
      ->get();
    
  3. ==============================

    3.대신에

    대신에

        ->where('shares.user_id', 'followers.follower_id')
    

    그것은해야한다

        ->whereRaw('shares.user_id=followers.follower_id')
    

    때문에 원래의 예에서 'followers.follower_id은'문자열로 해석됩니다.

  4. ==============================

    4.

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

    결과를 볼 수 있습니다.

    print_r($data[shares]);die;
    

    다른 쿼리에 대해 간단히 테이블의 설명을 제공

  5. ==============================

    5.

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

    구경하다

  6. from https://stackoverflow.com/questions/18388664/laravel-join-with-3-tables by cc-by-sa and MIT license