Pierce McGeough
Pierce McGeough

Reputation: 3086

Laravel Eloquent Join

I have two tables and I want to join them. I have looked at other examples and just can't figure it out.

My tables are as follows.

A club has many members
A member belongs to a club

I can list my clubs and after listing my clubs i can list the members of the club ok, but what I want to do is list all my members and show their club. So my output would be ID, Name, Club Name

This is my code setup so far

// clubs controller
public function index()
{
    $clubs = Club::all();
    return View::make('clubs.list')->with('clubs', $clubs);
}

public function show($id)
{
    $club = Club::findOrFail($id);
    $members = $club->Members()->get();
    return View:: make('clubs.show')->with('club', $club)->('members', $members);
}

// club model
class Club extends Eloquent
{
    // each club has many members
    public function Members()
    {
        return $this->hasMany('Member');
    }
}


// members controller
public function index()
{
    $members = Member::all();
    return View::make('members.list')->with('members', $members);
}

// member model
class Member extends Eloquent
{
    // each member belongs to one club
    public function club()
    {
        return $this->belongsTo('Club');
    }
}

Upvotes: 1

Views: 2449

Answers (1)

The Alpha
The Alpha

Reputation: 146269

In your Member model declare the following relationship method:

public function club()
{
    return $this->belongsTo('Club');
}

So now you can query all members with their Club info as:

$members = Member::with('club')->get();

In your View when looping the Members you may try something like this:

@foreach($members as $member)
    {{ $member->name }}
    {{ $member->club->name }}
@endforeach

This is not Eloquent Join but using it's relationship technique you may do it as given above, if you want to join then you may try something like this:

$members = Member::join('clubs', 'members.club_id', '=', 'clubs.id')
                 ->select('members.*', 'clubs.name as club_name')
                 ->get();

In this case, you may loop and use the Club info like this;

@foreach($members as $member)
    {{ $member->name }}
    {{ $member->club_name }}
@endforeach

Upvotes: 3

Related Questions