Laravel有许多关系没有循环显示结果


Laravel hasMany relationship not looping through to display results

通过外键,警报可以有许多消息与其关联。发送的每条消息也通过一个外键附加到一个用户。在查看警报时,如果存在此类消息(它们不是必需的),我希望显示每条消息以及相关用户的详细信息。

用户型号:

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

警报型号:

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

我注意到,如果警报没有任何相关消息,则forloop不起作用!

在我的show视图中,我有:

@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 

如果有消息要显示,但它只循环通过第一条消息,而不是其他消息,那么这非常有效。控制器拉入数据是:

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

关于为什么forloop在少于2个结果时不起作用,以及为什么它只循环通过第一个结果的任何指导。非常感谢。

首先,我建议对相关模型使用热切加载,否则您将运行许多您不想要也不需要的数据库查询:

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

然后在您查看旋转消息,而不是警报,因为您没有太多消息:

@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