Bandicood
Bandicood

Reputation: 35

Laravel resource::all with values from another table

I'm learning Laravel right now and i have following tables and resources (models, controllers, ect.):

tickets
- id
- title
- projectID
- statusID

projects
- id
- title

status
- id
- title

I have to make a list of my Tickets on the Startpage. Not nessesary to say that i need the Project- and Statustiltles and not the IDs. Currently i do:

Route::get('/', function()
{
    $tickets = Ticket::all();
    return View::make('layout')->with('tickets', $tickets);
});

My current output is:

tickets->id, tickets->title, tickets->projectID, tickets->statusID

The output i want is

tickets->id, tickets->title, tickets->projects->title, tickets->status->title

So i hope anyone can understand what i'm trying to ask here and maybe provide me some help. Thank you!


Resolution: I had to set the foreign_keys first in my DB. Then i used the relationships mentioned in the answers and it works fine.

My Model:

class Ticket extends \Eloquent {
    protected $fillable = [];

    public function project()
    {
        return $this->hasOne('Project', 'id', 'projectID');
    }

    public function status()
    {
        return $this->hasOne('Status', 'id', 'statusID');
    }
}

My View:

@foreach($tickets as $key => $value)
...
  <td>{{ $value->project->title }}</td>
  <td>{{ $value->status->title }}</td>
...
@endforeach

Upvotes: 0

Views: 3027

Answers (2)

Patrick Maciel
Patrick Maciel

Reputation: 4944

If you configure you relationships correctly you can do that without problems using the Laravel Eager Loading feature, for example:


Eager Loading (Laravel docs)

Eager loading exists to alleviate the N + 1 query problem...

class Ticket extends Eloquent {

    public function project()
    {
        return $this->belongsTo('Project', 'projectID', 'id');
    }

    public function status()
    {
        return $this->belongsTo('Status', 'statusID', 'id');
    }

}

Now, just call the fields you want, for example:

foreach (Ticket::all() as $ticket)
{
    echo $ticket->project->title;
    echo $ticket->status->title;
}

Obs.: In your return object/array you can't see the relationships fields unless you do manual joins, etc. So, just configure your relationships and call the fields you want.

Sorry for my english

Upvotes: 3

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

Define relationships specifying custom foreign keys (defaults would be status_id and project_id for your models):

// Ticket model
public function project()
{
    return $this->belongsTo('Project', 'projectID');
}

public function status()
{
    return $this->belongsTo('Status', 'statusID');
}

Then eager load related models:

$tickets = Ticket::with('project','status')->get();

// accessing:
foreach ($tickets as $ticket)
{
   $ticket->status; // Status model with all its properties
   $ticket->project; // Project model
}

Upvotes: 0

Related Questions