简体   繁体   中英

Laravel hasMany relationship not looping through to display results

An alert can have many messages associated with it, through a foreign key. Each message sent is also attached to a user, through a foreign key. On viewing the alert, if such messages exist (they are not required), I want to display each message, along with the associated user's details.

User model:

public function alerts()
{
    return $this->hasMany('Alert');
}

public function messages()
{
    return $this->hasMany('Message');
}

Alert model:

public function user()
    {
        return $this->belongsTo('User');
    }

    public function messages()
    {
        return $this->hasMany('Message');
    }

I have noticed if the alert doesn't have any messages associated with it, the forloop doesn't work!

Within my show view, I have:

@foreach($alerts as $alert)
    <tr>
        <td>{{ $alerts->messages->first()->firstname }}</td>
        <td>{{ $alerts->messages->first()->user->email }}</td>
        <td>{{ $alerts->messages->first()->user->phone_number }}</td>
        <td>{{ $alerts->messages->first()->message }}</td>
        <td>{{ date("j F Y", strtotime($alerts->messages->first()->created_at)) }}</td>
        <td>{{ date("g:ia", strtotime($alerts->messages->first()->created_at)) }}</td>
    </tr>
@endforeach 

Which works great, if there are messages to show, but it only loops through the first message, not the rest of them. The controller pulling in the data is:

public function show($id)
    {
        $alert = Alert::where('id','=',$id)->first();
        $this->layout->content = View::make('agents.alert.show', 
            array('alerts' => $alert));
    }

Any guidance as to why the forloop doesn't work when there is less 2 results, and why it only loops through the first result. Thank you.

First I suggest using eager loading for related models or you will run many db queries that you don't want nor need:

public function show($id)
{
    $alert = Alert::with('messages.user')->where('id','=',$id)->first();
    $this->layout->content = View::make('agents.alert.show', array('alert' => $alert));
}

Then in you view spin through messages, not alerts as you don't have many of them:

@foreach($alert->messages as $message)
<tr>
    <td>{{ $message->firstname }}</td>
    // if you are sure there is a user for each message, otherwise you need a check for null on $message->user
    <td>{{ $message->user->email }}</td>
    <td>{{ $message->user->phone_number }}</td> 
    <td>{{ $message->message }}</td>
    <td>{{ date("j F Y", strtotime($message->created_at)) }}</td>
    <td>{{ date("g:ia", strtotime($message->created_at)) }}</td>
</tr>
@endforeach

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