Laravel Eloquent - how to join a table
I am working on an API for my application.
I am trying to pull items from a database and return them to a JSON object, my items table looks like this:
Items
-id
-name
-description
-price
-currency_id
-company_id
this is how i get the items:
$rows = Company::where('guid',$guid)
->first()
->items()
->orderBy('name', $sort_order);
I want to replace currency_id with a currency object that contains all columns of the currency table
so my result would 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
+3
source to share
2 answers
Edit 2: The user issue was more complex than this since pagination and search was done with the request. Helped with https://pastebin.com/ppRH3eyx
Edit: I checked the code. So here.
In the company model
public function items()
{
return $this->hasMany(Item::class);
}
In the 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 it.
$rows = Company::with('items.currency')
->where('guid', $guid)
->first()
->items()
->orderBy('name', $sort_order);
+2
source to share