category classifies one-to-many commodities product, merchandise one-to-one commodity names productname
$arr= Category::select ("id","name")-> with ([" products"= > function ($query) {
) $query->select("id","category_id");}])
->with(["products.productname"=>function($query){
$query->select("product_id","name");}])
->orderby("id","desc")
->whereIn("id",[1,2,3])
->get();
return $arr;
[{
]"id": 3,
"name": "c",
"products": []
}, {
"id": 2,
"name": "b",
"products": []
}, {
"id": 1,
"name": "a",
"products": [{
"id": 1,
"category_id": 1,
"created_at": null,
"updated_at": null,
"productname": {
"product_id": 1,
"name": "hello"
}
}, {
"id": 2,
"category_id": 1,
"created_at": null,
"updated_at": null,
"productname": null
}]
}]
question
1, the first closure $query- > select ("id","category_id");}]) Hidden fields don"t seem to work?
2. I think "productname": {
"product_id": 1,
"name": "hello"
} product
become like this
"products": [{
"id": 1,
"category_id": 1,
"created_at": null,
"updated_at": null,
"product_id": 1,
"name": "hello"
}