laravel中提取最新时间戳的一对多关系

时间:2017-01-18 10:10:19

标签: php laravel laravel-5.3

我在数据库中有一对多的关系,我正在尝试提取最新的。表名为notificationalertFrequency,每个都有模型。我想写一个查询,它将获取与通知表中特定网站相关的最新时间戳。 alertFequency表只有2列,即notification_idcreated_at。以下是我的模型通知modl

   class Notification extends Model
{
    protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];

    public function statuses(){
        return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
    }

    public function alertFrequencies(){     
        return $this->hasMany('App\AlertFrequency');
    }
    // trail versions
    public function alert(){
        $items = AlertFrequency::select('alertFrequencies.created_at')//Any column you want to fetch
        ->join('notifications', 'notifications.id', '=', 'alertFrequencies.notification_id')
        ->orderBy('alertFrequencies.created_at','desc')
        ->first();
        if($items == null){
            return null;
        }
        return $items->created_at->toDateTimeString();

class AlertFrequency extends Model{
    protected $table = 'alertFrequencies';
    public function notification(){
        return $this->belongsTo('App\Notification');
    }  
}

notification模型中我编写了一个函数,该函数有望提取数据(即notification表中特定网站的最新时间戳),而不是notification_id是一个外键。 alertFrequency表。警报功能如下

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

返回created_at时间戳,但不是与特定网站相关的latset。我会帮助你吗?

在数据库中我有两个网站在12:18添加一个,第二个在12:24 .....抱歉我不知道如何在这里发布数据库。

1 个答案:

答案 0 :(得分:0)

直接您无法对需要使用orderBy()

的关系应用join()

试试吧。希望它有所帮助

$alert_timestamp = AlertFrequency::select('alertFrequencies.created_at')//Any column you want to fetch
    ->join('notification', 'notification.notification_id', '=', 'alertFrequencies.notification_id')
    ->orderBy('alertFrequencies.created_at','desc')
    ->get();