首页 > 解决方案 > 雄辩查询中的“where”,连接了3个表

问题描述

我有三个使用 eloquent 加入的表,查询看起来像这样

    $truck = TCategory::with('truck_categories.touch_points')->get();


    if(count($truck) > 0) {
        return response()->json(array('result' => $truck));
    } else {
        return response()->json(array('result' => 'No Trucks.'));
    }

回应是这样的:

{
"result": [{
    "id": 6,
    "name": "western",
    "created_at": null,
    "updated_at": null,
    "truck_categories": [{
        "id": 9,
        "touch_point_id": 8,
        "t_category_id": 6,
        "created_at": null,
        "updated_at": null,
        "touch_points": {
            "id": 8,
            "brand_id": 1,
            "user_id": 11,
            "base_latitude": 3.104193,
            "base_longitude": 101.610487,
            "name": "testing ok",
            "approved": 1,
            "driver": null,
            "created_at": "2018-04-25 07:43:49",
            "updated_at": "2018-04-25 07:45:27",
            "menu_id": 1,
            "location": "Kelana Jaya, 47300 Petaling Jaya, Selangor, Malaysia",
            "service_on_off": 1,
            "slug": "testing-ok",
            "image": null,
            "position": {
                "lat": 3.104193,
                "lng": 101.610487
            }
        }
    }]
}, ...

touch_points 出现在 truck_categories 中,我想在查询中添加 where 条件,有人可以帮我吗?提前致谢。

标签: laravel-5.5

解决方案


您可以将 where 条件设置如下:

$truck = TCategory::with(['truck_categories.touch_points' => function($query){
                          $query->where('<Put your condition here>');
                        }])->get();

if(count($truck) > 0) {
    return response()->json(array('result' => $truck));
} else {
    return response()->json(array('result' => 'No Trucks.'));
}

推荐阅读