如何使用req-> id连接表

问题描述 投票:1回答:2
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)。

php laravel
2个回答
1
投票

由于您使用模型,因此可以使用Eloquent关系来加载相关数据。首先,define a relationship模型中的Tour

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,则将代码的第一部分替换为: -

public function getTourDetail(Request $request)
    {
        $tour = Tour::where('id',$request->id)->first();
© www.soinside.com 2019 - 2024. All rights reserved.