2017-12-30 28 views
1
public function getTourDetail(Request $req) 
{ 
    //Get link detail 
    $tour = Tour::where('id',$req->id)->first(); 
    //I want to take location.city of the location table 
    $detail = Tour::join('location','tour.id_location','=','location.id') 
    ->whereColumn([ 
     ['tour.id_location','=','location.id'] 
    ]) 
    ->get(array(
     'tour.id as id_tour', 
     'location.image', 
     'tour.name', 
     'tour.id_location', 
     'location.city' 
    )); 
    return view('page.tour-detail',compact('tour','detail')); 
} 

두 개의 쿼리 문을 결합하여 링크 요청 ID ($ tour)와 같은 위치 테이블 ($ detail)의 정보를 얻을 수 있기를 원합니다.req-> id를 사용하여 테이블을 조인하는 방법

답변

1

모델을 사용하기 때문에 Eloquent 관계를 사용하여 관련 데이터를로드 할 수 있습니다. 첫째, Tour 모델 define a relationship :

public function location() 
{ 
    return $this->belongsTo(Location::class, 'id_location') 
} 

그런 다음 Tour를로드 및 관련 위치 얻을 :

$tour = Tour::find($req->id); 
$relatedLocation = $tour->location; 
0

우선을, 당신이 처리하는 더 좋은 생각이 될 것 웅변 관계를 사용하여 다음 모델을 사용하는 경우 너 같은 상황이야. 그러나 당신이 당신의 테이블에 가입하려면 다음이 방법이있을 것입니다 :

public function getTourDetail($id) 
{ 
    $tour = Tour::where('id',$id)->first(); 
    //I want to take location.city of the location table 
    $detail = DB::table('location') 
         ->join('tour','tour.id_location','=','location.id') 
         ->select(
          'tour.id as id_tour', 
          'location.image', 
          'tour.name', 
          'tour.id_location', 
          'location.city' 
         )->get(); 
    return view('page.tour-detail',compact('tour','detail')); 
} 

참고 : 제출 양식에서 id을 얻는 경우 다음과 코드의 제 1 부분을 대체 : -

public function getTourDetail(Request $request) 
    { 
     $tour = Tour::where('id',$request->id)->first();