mercredi 25 novembre 2015

How to easily define relationships of a pivot table where the third column is a foreign key to another table in laravel.

I am new to laravel 5. I have been working on a client app where I have setup a relationship like so:

  1. Many to Many relationship between Application and Cart giving me an application_cart table with columns

    • application_id
    • cart_id

Sample Model

class Application extends Eloquent
  {
    public function carts()
    {
        return $this->belongsToMany('App\Cart');
    }

  }

  class Cart extends Eloquent 
  {
        public function applications()
    {
        return $this->belongsToMany('App\Application');
    }

  }

Using the model above, I have been able to display records beautifully in views like below:

 @foreach($cart->applications as $application)
    <td>{{ $application->student->last_name }}</td>
    <td>{{ $application->student->first_name }}</td>
 @endforeach

Recently, the client has changed specification so that I have the addition of a third column supervisor_id on the pivot resulting to a pivot table structure like so:

application_cart table

  • application_id
  • cart_id
  • supervisor_id (Foreign key to the supervisors table. A Supervisor Model exist already)

The goal is so that I can now be able to display an output like below:

 @foreach($cart->applications as $application)
        <td>{{ $application->student->last_name }}</td>
        <td>{{ $application->student->first_name }}</td>
        <td>
            {{ $application->supervisor->user->name }} <!-- Display the "supervisor name" assign to the application (How can I beautifully display the supervisor name)-->
        </td>
   @endforeach

How can I easily integrate this new spec in my code?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire