在laravel中使用拖曳带

问题描述 投票:1回答:1

使用laravel 7并说我有三个桌子

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

并且在产品模型内部,我有此方法

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

并且在product_units内部,我有此方法

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

现在如果我想退货,我可以做到..

return Product::find(1);

所以我得到了这个回报

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

如果我希望退货有关系,我可以执行此代码

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

这将返回这样的json ..

[
    {
        "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_relations一起使用其他->返回产品时-> with('get_unit_relations')

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

获得这样的结果..

[
    {
        "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',
                    }
                ]
            }
        ]
    }
]

我想要的是返回产品,并具有许多product_units和hasOne单元来访问该单元的名称非常感谢..

php laravel eloquent many-to-many one-to-many
1个回答
1
投票

我找到了添加get_unit_id这样的解决方案

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

及其工作非常感谢大家..

© www.soinside.com 2019 - 2024. All rights reserved.