Laravel with problem

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"

}
Feb.21,2022

first question: the second with generates two relation, [products,products.productname]. After calling with twice, the products of the first with is replaced by the second

this can be avoided by calling with: only once

with([
            'products' => function($query) {
                return $query->select(['id', 'category_id']);
            },
            'products.productname' => function($query) {
                return $query->select(['product_id', 'name']);
            },
        ])

has the second problem been solved? I want to do the same. Now it's time to traverse and deal with it again

.
Menu