[英]Laravel Eloquent - how to join a table
I working on an API for my app. 我为我的应用程序开发了一个API。
I'm trying to pull items from the database and return them in JSON object, my items table looks like this: 我正在尝试从数据库中提取项目并将它们返回到JSON对象中,我的项目表如下所示:
Items
-id
-name
-description
-price
-currency_id
-company_id
this is how I'm getting the items: 这就是我得到这些物品的方式:
$rows = Company::where('guid',$guid)
->first()
->items()
->orderBy('name', $sort_order);
I want to replace the currency_id with a currency object that contains all the columns of currency table 我想用一个包含货币表所有列的货币对象替换currency_id
so my result will be like this: 所以我的结果将是这样的:
[
{
'id':'1',
'name':'name',
'description': 'example',
'price':'100',
'currency':{
'id':'1',
'name':'usd',
'symbol': '$'
}
}
]
update : This is my currencies table: 更新 :这是我的货币表:
id
name
symbol
code
Try below 试试以下
Make one relationship in Item Model 在物料模型中建立一个关系
public function currencies() {
return $this->hasMany('App\Currency');
}
then do below in your controller 然后在你的控制器下面做
$row=Items::All()->with('currencies');
Edit 2: The user's problem was more complex than this since there was pagination and search integration with the query. 编辑2:用户的问题比这更复杂,因为有分页和搜索与查询集成。 Helped with https://pastebin.com/ppRH3eyx 帮助https://pastebin.com/ppRH3eyx
Edit : I've tested the code. 编辑:我已经测试了代码。 So here. 所以在这里。
In Company model 在公司模型中
public function items()
{
return $this->hasMany(Item::class);
}
In Item model 在物料模型中
public function currency()
{
return $this->belongsTo(Currency::class);
}
Controller logic 控制器逻辑
$items = Company::with(['items' => function($query) use ($sort_order) {
$query->with('currency')->orderBy('name', $sort_order);
}])
->where('guid', $guid)
->first()
->items;
Result with test data 测试数据的结果
[
{
"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"
}
}
]
Try this. 试试这个。
$rows = Company::with('items.currency')
->where('guid', $guid)
->first()
->items()
->orderBy('name', $sort_order);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.