Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent - how to join a table

Tags:

I working on an API for my app.

I'm trying to pull items from the database and return them in JSON object, my items table looks like this:

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

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
like image 584
Ilan Finkel Avatar asked May 19 '17 05:05

Ilan Finkel


1 Answers

Edit 2: The user's problem was more complex than this since there was pagination and search integration with the query. Helped with 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);
like image 186
Sandeesh Avatar answered Oct 13 '22 00:10

Sandeesh