简体   繁体   中英

Display Table Join result

I have an existing Join on in my Laravel Project with joins a member to their Rank

I have a Rankmapping table and a Members Detail table. in the Members Detail, the Rank field is the id of the Rankmapping table.

On the code below, I have a basic join for the MembersController@index page which works perfect.

However I can't get the join to work on the MembersController@show page I would like the Rank to show here as I will need the use to be able to edit this rank as a member is promoted through the ranks.

HTML Page (MemberController@show)

@section('content')
 <div class="container-fluid">

    <div class="row">
        <div class = "col-sm-12">
            <div class = "card">
                <div class="card-header card-header-icon card-header-rose">
                    <h4 class="card-title font-weight-bold">Member Details</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <tr>
                            <th>First Name:</th>
                            <td style="border-top: 1px #ddd solid">{{$member->first_name}}</td>
                            <th>Last Name:</th>
                            <td style="border-top: 1px #ddd solid">{{$member->last_name}}</td>
                            <th>Rank:</th>
                            <td style="border-top: 1px #ddd solid">{{$member->rank}}</td>
                        </tr>
                        <tr>
                            <th>Age:</th>
                            <td>{{$member->age}} years</td>
                            <th>Date of Joining:</th>
                            <td>{{date("d/m/Y",strtotime($member->date_joined))}}</td>
                            <th>Service:</td>
                            <td>{{number_format((float)$member->service,2)}} years</td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>

HTML Page (MembersController@Index)

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-header card-header-icon card-header-rose">
                    <h4 class="card-title text-center">Members</h4>
                </div>
                <div class="card-body">
                    <div class="pull-right new-button">
                        <a href="{{action('MembersController@create')}}" class="btn btn-primary" title="Add Member"><i
                                    class="fa fa-plus fa-2x"></i> Add Member</a>
                    </div>

                    <div class="table-responsive">
                        <table class="table">
                            <thead class="text-primary">
                            <th></th>
                            <th class="text-center">Membership Number</th>
                            <th class="text-center">Name</th>
                            <th class="text-center">Rank</th>
                            </thead>
                            <tbody>
                                @foreach($member as $m)
                            <tr>
                                <td class="text-center">
                                <a href="{{action('MembersController@show', $m->id)}}" title="View" class="btn btn-success"><i class="fa fa-info"></i></a>
                                </td>
                                <td class="text-center">{{$m->membership_number}}</td>
                                <td class="text-center">{{$m->last_name}}, {{$m->first_name}}</td>
                                <td class="text-center">{{$m->memberrank}}</td>
                            </tr>
                                @endforeach
                            </tbody>
                            <tfooter>
                                <tr>
                                </tr>
                            </tfooter>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection

This is my Member.php file

class Member extends Model
{
//
protected $fillable = [
    'id', 'membership_number', 'first_name', 'last_name', 'rank', 'date_joined', 'date_birth', 'active'
];

public function getAgeAttribute()
{
    return Carbon::parse($this->attributes['date_birth'])->age;
}

public function getServiceAttribute()
{
  $now = Carbon::now();

  $service = Carbon::parse(date('Y-m-d',strtotime($this->date_joined)))->DiffInYears($now);
  return $service;  
}

public function ActiveKids()
{
    return $this->hasMany('App\ActiveKids', 'member_id', 'id');
}

public function MemberRank()
{
    return $this->hasOne('App\Rankmapping', 'rank', 'members_rank');
}
} 

This is my MembersController

class MembersController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    //
    $member = DB::table('members')
            ->join('rankmappings', 'members.rank', '=', 'rankmappings.id')
            ->select('members.*', 'rankmappings.rank as memberrank')
            ->orderBy('last_name')
            ->get();

    return view('members.index', compact('member'));
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    //

    return view('members.add');
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //
 $validateData  = Validator::make($request->all(), [
     'membership' => 'required',
     'firstname' => 'required',
     'lastname' => 'required',
     'doj' => 'required|date',
     'dob' => 'required|date',
 ]);

 if ($validateData->fails())
 {
     return Redirect::back()->withErrors($validateData)->withInput();
 }

    //Create Member
    $e = new Member();
    $e->membership_number = $request->get('membership');
    $e->first_name = $request->get('firstname');
    $e->last_name = $request->get('lastname');
    $e->rank = "";
    $e->date_joined = $request->get('doj');
    $e->date_birth = $request->get('dob');
    $e->active= "Y";
    $e->save();

    return redirect(action('MembersController@index'))->with('success', 'Member Added');
}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    //
    $member = Member::find($id);

    if ($member !=null)
    {
        return view('members.show', compact('member', 'service', 'mrank'));

    }

    return redirect(action('MemberController@index'));
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */

Instead of using join() , you could do a query using the Model itself in order to be able to use Eloquent calls like the with() method. With it you could include the rank relationship using with('MemberRank') or just call the Relationship directly.

The code would look something like this:

use App\Member; // Important! Import your model

public function index()
{
    $member = Member::with('MemberRank')
            ->orderBy('last_name')
            ->get();

    return view('members.index', compact('member'));
}

public function show($id)
{
    $member = Member::findOrFail($id);

    return view('members.show', compact('member'));
}

Then on the views you would call it like this:

<td class="text-center">{{$member->MemberRank->rank}}</td>

Tip: When using Eloquent to make a query you can just call the relationships without even using with() or load() that it will make the query to get it automatically. But beware: If you call it for every member of a list it would make as many queries as that list has members.

The way around it is to use Eager Loading, to load it into the variable before calling for the data. You can read about it here: Eloquent: Relationships/#Eager Loading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM