mysql - 连接 3 个数据库表以在 Laravel 中获取 JSON 结果

标签 mysql json laravel-4 jsonresult

我有 3 个数据库表:国家、城市和餐厅

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 响应中获取每个城市的餐馆?

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用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();

关于mysql - 连接 3 个数据库表以在 Laravel 中获取 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439111/

相关文章:

mysql - 获取总消耗

php - JSON -> Xcode 字符串格式

javascript - 从 json_encode 脚本创建不带双引号的数组

php - 在 Laravel 4 中将数据传递给闭包

mysql - Laravel 迁移 - 未创建表

c++ - Qt C++ MySQL 到 QTableView 多个连接表为空

MySQL - 如何创建无主视图?

mysql - 如何编写mysql查询来获取想要的数据?

javascript - 如何在JS中向具有特定参数/值的子对象添加属性?

php - 如何在 Laravel 的验证器中更改数据库