【问题标题】:Laravel hasMany relationship not looping through to display resultsLaravel hasMany 关系没有循环显示结果
【发布时间】:2014-06-04 00:58:00
【问题描述】:

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

用户模型:

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

【问题讨论】:

    标签: php for-loop laravel laravel-4


    【解决方案1】:

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

    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
    

    【讨论】:

    • 像魅力一样工作。关于急切加载也非常清楚。非常感谢,Deczo。
    • 谢谢!我遇到了同样的问题,但我尝试使用 $alert->messages() 进行 foreach 循环
    猜你喜欢
    • 1970-01-01
    • 2022-11-23
    • 2016-07-12
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多