如何使用req-> id连接表格

时间:2017-12-30 16:20:15

标签: php laravel

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

我希望能够组合两个查询语句来获取位置表($ detail)中的信息,例如链接请求的ID($ tour)。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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,请将代码的第一部分替换为: -

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