【问题标题】:Join 3 database tables to get JSON Result in laravel在 laravel 中加入 3 个数据库表以获取 JSON 结果
【发布时间】:2016-07-26 03:31:14
【问题描述】:

我有 3 个数据库表:Country、City 和 Restaurant

Country     {id,name}
City        {id,name,country_id}
Restaurant  {id,name,city_id}

如何检索国家/地区的城市和餐厅信息?

我正在使用此代码来获取具有城市的国家/地区: 请注意,我将表之间的所有关系设置如下:

Country {hasMany('City')}
City    {hasMany('Hotel')}
City    {belongsTo('Country')}
Hotel   {belongsTo('City')}

$x = Country::with('city')->get();
return Response::json($x,200,[],JSON_PRETTY_PRINT);

结果:

[
    {
        "id": 1,
        "name": "Spain",
        "city": [
            {
                "id": 1,
                "name": "Madrid",
                "country_id": 1
            },
            {
                "id": 2,
                "name": "Barcelona",
                "country_id": 1
            }
        ]
    },
    {
        "id": 2,
        "name": "Italy",
        "city": []
    }
]

我应该怎么做才能在同一个 JSON 响应中获取每个城市的餐馆?

任何帮助将不胜感激。

【问题讨论】:

    标签: mysql json laravel-4 jsonresult


    【解决方案1】:

    您可以使用hasManyThrough() 访问远程关系: https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

    // App\Country
    public function hotels() {
        $this->hasManyThrough('App\Hotel', 'App\City');
    }
    

    那么你可以像这样获取它:

    $x = Country::with('city')->with('hotels')->get();
    

    【讨论】:

    • 谢谢,它成功了。但是我如何才能获得一个国家/地区内的所有酒店@maximl337?
    • $x=Country->with("city")->with("hotels")->where("country", "=" , "US")->get(); $hotels = $x->hotels;如果你也想过滤酒店 `$hotels = $x->hotels()->where("city_id" , "=", 15)->get();
    猜你喜欢
    • 2018-01-19
    • 2014-10-10
    • 1970-01-01
    • 2012-07-04
    • 2018-02-01
    • 2019-04-28
    • 2020-12-26
    • 1970-01-01
    相关资源
    最近更新 更多