我正在为我的应用开发 API。
我正在尝试从数据库中提取项目并将它们返回到 JSON 对象中, 我的项目表如下所示:
Items
-id
-name
-description
-price
-currency_id
-company_id
这是我获取元素的方式:
$rows = Company::where('guid',$guid)
->first()
->items()
->orderBy('name', $sort_order);
我想用包含货币表所有列的货币对象替换 currency_id
所以我的结果会是这样的:
[
{
'id':'1',
'name':'name',
'description': 'example',
'price':'100',
'currency':{
'id':'1',
'name':'usd',
'symbol': '$'
}
}
]
更新: 这是我的货币表:
id
name
symbol
code
最佳答案
编辑 2:用户的问题比这更复杂,因为分页和搜索与查询集成。帮助 https://pastebin.com/ppRH3eyx
编辑:我已经测试了代码。所以在这里。
在公司模型中
public function items()
{
return $this->hasMany(Item::class);
}
在项目模型中
public function currency()
{
return $this->belongsTo(Currency::class);
}
Controller 逻辑
$items = Company::with(['items' => function($query) use ($sort_order) {
$query->with('currency')->orderBy('name', $sort_order);
}])
->where('guid', $guid)
->first()
->items;
带有测试数据的结果
[
{
"id": 2,
"name": "Toy",
"description": "Random text 2",
"price": 150,
"company_id": 1,
"currency_id": 1,
"currency": {
"id": 1,
"name": "usd",
"symbol": "$",
"code": "USD"
}
},
{
"id": 1,
"name": "Phone",
"description": "Random text",
"price": 100,
"company_id": 1,
"currency_id": 1,
"currency": {
"id": 1,
"name": "usd",
"symbol": "$",
"code": "USD"
}
}
]
试试这个。
$rows = Company::with('items.currency')
->where('guid', $guid)
->first()
->items()
->orderBy('name', $sort_order);
关于php - Laravel Eloquent - 如何加入表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44062386/