Laravel 如何获取所有 Child 数据属于 parent orderby desc?

Laravel How to get all Child data belongs parent orderby desc?

所以我想从 parent data order by id descending/recent 中获取所有 child 数据像这样存储

{
list parent data recent : {
 "List data": {
        "id": 2,
        "title": "Test",
        "number": "10231232",
        "created_at": null,
        "updated_at": null
    },
    "All child by parent id": [
        {
            "id": 5,
            "title": "lalala",
            "parent_id": 2,
            "created_at": null,
            "updated_at": null
        },
    }
}

在我的控制器中,我创建了代码 model::where() 函数,但我不知道格式在哪里,我使用此代码查找 parent 数据并且 child 属于 id parent,我想使用此代码获取最近的 parent 数据和 child。谢谢

 public function recent(){
        try{
            $parent = $this->parent->orderBy('id', 'desc')->limit(1)->get();
            $child= Child::where('parent_id', '=', $parent)->get();
            return response()->json(['List parent recent' => $parent , 'all child data' => $child], 300);
        }catch (ModelNotFoundException){
            return response()->json(['Error' => '404', 'Message' => 'Item not found or not created yet!'], 404 );
        }

    }

我尝试过此代码并在邮递员处存储数据,但问题是 child 数据不存在

 {
    "List updates recent": [
        {
            "id": 2,
            "title": "uasda",
            "version": "6969",
            "created_at": null,
            "updated_at": null
        }
    ],
    "All features by id": []
}

你错了,在这一行

Child::where('parent_id', '=', $parent)

您正在将 id 与对象进行比较,这将 return null,

试试这个

 public function recent(){
        try{
            $parent = $this->parent->orderBy('id', 'desc')->firstOrFail();
            $child= Child::where('parent_id', $parent->id)->get();
            return response()->json(['List parent recent' => $parent , 'all child data' => $child], 300);
        }catch (ModelNotFoundException){
            return response()->json(['Error' => '404', 'Message' => 'Item not found or not created yet!'], 404 );
        }

    }