user860511
user860511

Reputation:

Laravel - Select just one row from pivot table and return data

Currently, for a user, I can return all matches correctly.

public function getMatches()
{
    $matches = Criteria::whereUserId( Auth::id() )
    ->has('alerts')
    ->with('alerts.location', 'alerts.user.companies')
    ->get();

    $this->layout->content = View::make('users.alert.matches', 
        array('matches' => $matches));
}

Relationship:

A Criteria belongsToMany Alerts and an Alert belongsToMany Criterias.

Problem:

If the user wishes to see more information about a certain match, I want to get just that result from the database. On my view, I can access the criteria_id inside the first forloop, and the alert_id inside the second forloop.

@foreach($matches as $match)
    {{$match->id}}
        @foreach($match->alerts as $alert)
            {{$alert->id}}
        @endforeach
@endforeach

But how can I use these variables to select just one pivot table match that the user wants to view more information about?

If a user was to select a certain {{$alert->id}}, how do I find which criteria_id relates to that alert_id, and then query the database to return the just that row of information, both from the criteria table and alert table, along with the with-> statement shown above.

Many thanks for your help.

Upvotes: 0

Views: 4366

Answers (1)

Johnson
Johnson

Reputation: 330

I think you can include the data in your pivot table to your eager loading, like this:

public function getMatches()
{
    $matches = Criteria::whereUserId( Auth::id() )
    ->has('alerts')
    ->with('alerts.location', 'alerts.user.companies')
    ->withPivot('foo', 'bar'); //pivot table columns you need from pivot table criteria_alert
    ->get();

    $this->layout->content = View::make('users.alert.matches', 
        array('matches' => $matches));
}

And access it like this:

@foreach($matches as $match)
    {{$match->id}}
        @foreach($match->alerts as $alert)
            {{$match->pivot->foo}} // pivot table data
            {{$alert->id}}
        @endforeach
@endforeach

Check out the laravel documentation for more details.

Also, this might help you simplify your code:

$matches = Auth::user()->with('criterias', 'criterias.alert')->get();

With your criteria to alert relationship like this:

return $this->belongsToMany('Alert')->withPivot('foo', 'bar');

Hope this helps.

Upvotes: 0

Related Questions