【发布时间】: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