在Eloquent中检索嵌套关系?

时间:2017-01-27 07:39:33

标签: php laravel eloquent

我有三种模式:

  1. 油漆
  2. 汽车
  3. 漆:

    {
        "id" : 1,
        "stuff" : "...",
        "car_id" : "4"
    }
    

    汽车:

    {
        "id" : 4,
        "other_stuff" : "...",
        "make_id" : "7",
    }
    

    请:

    {
        "id" : 7,
        "make_name" : "Toyota"
    }
    

    如果我希望能够获得以下结果而无需手动调用Make模型:

    // single Eloquent query to return: 
        {
            "id" : 1,
            "stuff" : "...",
            "car_id" : "4",
            "car" :     {
                "id" : 4,
                "other_stuff" : "...",
                "make_id" : "7",
                "make" :     {
                    "id" : 7,
                    "make_name" : "Toyota"
                }
            }
        }
    

    单一嵌套很好,因为你可以使用Paint :: with('car')。汽车模型有Car :: with('car'),但我不知道如何将两者结合起来。

1 个答案:

答案 0 :(得分:6)

使用nested eager loading

Paint::with('car.make')->get();
相关问题