Bravi
Bravi

Reputation: 773

Laravel merging relationships tables

I have two models (and two tables in the database) in Laravel 5: Artwork and Option (table names are artworks and options). A single artwork can have many options, so my models are as follows:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Artwork extends Model {

    public function options(){
        return $this->hasMany('App\Option');
    }

}

and

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Option extends Model {

    //

}

I'm trying to output an array that will contain ALL the artworks that will have their options nested inside them. Outputting only artworks works fine ($artworks = $artwork->get() as shown below), but I cannot figure out how to merge / nest options within each artwork.

Here is my Route for this

get('api/artworks','ArtworksController@index');

And here is my controller

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Artwork;

class ArtworksController extends Controller {


    public function index(Artwork $artwork)
    {
        $artworks = $artwork->merge($artwork->options())->get();
        return $artworks;
    }

}

I was playing around with that merge() function and I just couldn't get it right. Is it possible to achieve this with merge() at all?

Upvotes: 0

Views: 817

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153150

You just need to eager load the options relationship:

$artworks = $artwork->with('options')->get();

Upvotes: 1

Related Questions