doutou19761022 2017-01-18 06:27
浏览 1507
已采纳

Laravel:一对多关系只返回一条记录

I have a one to many relationship between notification and alerFrequencies table. they have models for both. I wrote this function to extract all the latest created_at time stamp from the alerFrequencies table.

Example, if I have one website in my notification table with created_at time stamps in the alert table, it should return me the latest time stamp only. If I have 2 websites in the notification table with a different time stamp, it should return the time stamp for the 2 websites apart.

Here it returns only the latest regardless of the number of websites in the notification table. ony one who get a better idea to write the query, i would appreciate all kinds of help and suggestions.

public function alert(){
        $alert_timestamp = AlertFrequency::with('notification')->select('created_at')->groupBy('created_at')->orderBy('created_at','DESC')->first();
        $alert_timestamp=$alert_timestamp->created_at->toDateTimeString();
        if($alert_timestamp==null){
            return false;
        }       
            return $alert_timestamp;
    }

in the database i have to tables notifications and alerFrequencies table, with one to many relationship. the notification_id is a foreign key in the alertFreqency table. notification has columns: is, website url and alertFrequencies has : id. notification_id and created_at. now i want to get the latest created_at for every website in the notification table.

  • 写回答

1条回答 默认 最新

  • dqpu4988 2017-01-18 09:55
    关注

    There are a few things that you are doing wrong. First you are querying AlertFrequency::with('notification') while from what I am understanding you might want something like Notification::with('alertfrequencies'). The second thing is that you are selecting just one column. Selecting just one column makes the with function useless. Third thing you are doing wrong is grouping by the created_at column. This simply does nothing for your needs. You would have to groupBy('notification_id'). I wrote the above explanations so you can understand better the logic of your application, while I am giving a possible solution below.

    Given that you want the latest timestamp of a notification for each website, then a possible approach would be to add an accessor in you Notification model.

    public function getLastTimestampAttribute(){
        return AlertFrequency::where('notification_id', $this->attributes['id'])->order_by('created_at','desc')->first()->created_at;
    }
    

    Then you can easily access the latest timestamp for each notification by doing $notification->last_timestamp, supposing that $notification is your object on the view.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部