0

I have two tables trails and markers (one trail can have many markers). I would like to return data from both using a custom method in the trails table.

Something like this:

public function RetrieveMarker(){
    return Marker::where("relation_id","=", $this->id);
}

but how do I call this method from a controller?

I would like to return a json object of several trails and their related markers like this:

[{id: 1, trail: a trail, markers: [{id: a marker}, id: another marker],}
{id: 2, trail: trail 2, markers: [{id: yam}, id: yaam]}]

and would like to do something like this:

return $this->trail               
            ->orderBy('title', 'ASC')
            ->where('region_id', $region_id)  
            ->RetriveMarkers()              
            ->get();   

but I am getting an illuminate/bad/query exception.

I have tried a couple of variations using scope but think that this isn't that difficult, I just don't know the way!

BTW, I am using Laravel 4, there isn't a direct relationship between trails and markers because markers is polymorphically related to several tables and I don't want to use the "$this->belongsTo" style as a custom method is definitely needed here.

Thanks in advance.

James Satori-Brunet
  • 901
  • 2
  • 13
  • 28

1 Answers1

0

You would need to have two models defined in your situation, Trail and Marker. Your Trail class will look like this, (I've omitted some of the other items for the sake of this example);

class Trail extends Eloquent
{

    protected $table = 'trails';

    public function markers()
    {
        return $this->hasMany('Marker');
    }
}

Your Marker model will be a basic Eloquent model object;

class Marker extends Eloquent
{
    protected $table = 'markers'; 
}

Now to create a query for all of your trails with the markers loaded you can use Eloquent's eager loading capabilities;

$trailsWithMarkers = $this->trail
     ->with('markers')
     ->orderBy('title', 'ASC')
     ->where('region_id', $region_id)
     ->get();

The secret sauce here is the ->with('markers') which instructs Eloquent to perform a join and load all of the markers associated with each trail object.

Finally to return JSON it's dead simple in Laravel. The get method on the end of that query returns a collection which Laravel understands and can serialise for you as simply as;

return Response::json($trailsWithMarkers);

I would suggest you have a read up of how Eloquent handles relationships.

marcus.ramsden
  • 2,633
  • 1
  • 22
  • 33
  • Thanks for the response. The problem is that the relationship between Trails and Markers is a polymorphic one and this approach won't work for that. – James Satori-Brunet Jun 28 '15 at 10:23
  • Ah sorry, missed the note about it being polymorphic. Just having a bit more of a read around would this help you http://stackoverflow.com/questions/26727088/laravel-eager-loading-polymorphic-relations-related-models? – marcus.ramsden Jun 28 '15 at 14:08