Laravel Eloquent Join

喜夏-厌秋 提交于 2019-12-23 03:46:25

问题


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.

  • Clubs
    • id
    • name
  • Members
    • id
    • club_id
    • name

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');
    }
}

回答1:


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


来源:https://stackoverflow.com/questions/25872376/laravel-eloquent-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!