【问题标题】:using tow with in laravel elequent在 laravel eloquent 中使用 tow
【发布时间】:2020-09-04 18:39:59
【问题描述】:

在使用 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,
            }
        ]
    }
]

我现在的问题是如何使用 other ->with 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',
                    }
                ]
            }
        ]
    }
]

我想要的是返回产品和 hasMany product_units 和 hasOne 单位来访问单位的名称 非常感谢..

【问题讨论】:

  • 我猜with('get_unit_relations','get_unit_relations.get_unit_id')->... 会成功

标签: php laravel eloquent many-to-many one-to-many


【解决方案1】:

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

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

它的工作感谢大家..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2021-09-29
    相关资源
    最近更新 更多