vendredi 20 mai 2016

Eager Loading Laravel 5 many-to-many relationship with two foreign keys

In my application, I have two tables, a Users table and a Forms table. The Users table is your typical user info with id, and the Forms table has a list of fields a user would need to complete. The many-many relationship is being tracked in my UserForms pivot table like so:

  • id
  • form_id (fk -> forms)
  • sender_id (fk -> users)
  • receiver_id (fk -> users)
  • completed

A user may send another user a form to that he/she needs to complete, and a user can both send and receive many forms. A form may therefore have many users associated with it. The problem is when I bring up a form and try to eager load the relationship containing the User info for both the sender and receiver (since there are two foreign keys). It seems like I can only do one or the other. My form model looks like so:

Form.php

class Form extends Model
{
    public function senders() {
        return $this->belongsToMany('App\User', 'user_forms', 'form_id', 'sender_id')->withPivot('receiver_id', 'completed');
    }

    public function receivers() {
        return $this->belongsToMany('App\User', 'user_forms', 'form_id', 'receiver_id')->withPivot('sender_id', 'completed');
    }
}

FormController:

public function show( $id )
{
    $form = Form::with('receivers')->findOrFail($id);  
    return view('form.show', ['form' => $form]);
}

view.blade.php

@foreach( $form->receivers as $receiver )
    <tr>
        <td> </td>
        <td> </td>
    </tr>
@endforeach

How can I get it to load the User attributed to sender_id, so I could do something like this in my view:



Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/25e6n6X
via IFTTT

Aucun commentaire:

Enregistrer un commentaire