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

时间:2014-04-19 16:13:10

标签: php for-loop laravel laravel-4

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

用户模型:

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个结果时不起作用的原因以及为什么它只循环第一个结果的任何指导。谢谢。

1 个答案:

答案 0 :(得分: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