简体   繁体   中英

using tow with in laravel elequent

in using laravel 7 and let say i have three table

+───────────+────────────────+────────+
| products  | product_units  | units  |  
+───────────+────────────────+────────+
| id        | id             | id     |  
| name      | product_id     | name   |  
| ect       | unit_id        |        |  
+───────────+────────────────+────────+

and inside Product model i have this method

public function get_unit_relations()
{
    return $this->hasMany('App\Models\Product_unit','product_id','id');
}

and inside product_units i have this method

public function get_unit_id()
{
    return $this->hasOne('App\Models\Unit','id','unit_id');
}

now if i want to return product i can do this..

return Product::find(1);

so i gat this return

[
    {
        "id": 1,
        "name": "test",
    }
]

and if i want the return to have a relation i can do this code

return Product::find(1)->with('get_unit_relations');

this will return json like this..

[
    {
        "id": 1,
        "name": "test",
        "get_unit_relations": [
            {
                "id": 3,
                "unit_id": 2,
                "product_id": 1,
                "barcode": "455",
                "smallest_unit_relation": 12,
                "price": 12,
            }
        ]
    }
]

my question now is how can i use other ->with with the get_unit_relations when return the product->with('get_unit_relations')

public function get_unit_id()
{
    return $this->hasOne('App\Models\Unit','id','unit_id');
}

to get result like this..

[
    {
        "id": 1,
        "name": "test",
        "get_unit_relations": [
            {
                "id": 3,
                "unit_id": 2,
                "product_id": 1,
                "barcode": "455",
                "smallest_unit_relation": 12,
                "price": 12,
                'get_unit_id':[ // how can i get the result with this method also to access the name of the unit
                    {
                        id:1,
                        name:'unit name',
                    }
                ]
            }
        ]
    }
]

what i want is return the product and hasMany product_units and hasOne unit to access the name of the unit thanks a lot..

i found the solution to add the get_unit_id like this

public function get_unit_relations()
{
    return $this->hasMany('App\Models\Product_unit','product_id','id')->with('get_unit_id');
}

and its worked thanks everyone..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM