2017-01-18 45 views
0

我在数据库中有一对多的关系,我试图提取最新的。表格名称为notificationalertFrequency,它们各自具有模型。我想编写一个查询,以便获取与通知表中特定网站关联的最新时间戳记。 alertFequency表只有2列,即notification_idcreated_at。以下是我的模型通知MODLlaravel中的一对多关系提取最新的时间戳

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; 
} 

它returnning created_at时间戳但不与特定网站LATSET。我会帮助你的帮助?

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

+1

你只是'选择''created_at'。所以它只返回它。你可以尝试在select()中添加你想要的字段,或者更好地解释你想实现的目标吗? – EddyTheDove

+1

我想要实现的是,当通知表中添加新网站时,新网站的notification_id将被添加到带有created_at时间戳的alertFrequency表中,并且可能会在通知表中添加许多网站,他们的notification_id是alerFrequency表中的外键,然后我想提取特定网站的最新created_at。 –

回答

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(); 
+0

tnx我得到了新的见解。我会试试你的方式! –

+0

我已经投了你的答案。我有个问题。我添加到通知表中的网站。在数据库中,这两个网站有不同的时间戳,当我有var_dumo它时,它只给了我最后一次戳2次。我期望得到的是两个网站的时间戳,而不仅仅是时间戳2次。 –

+0

@abrahamfoto你已经接受了答案没有upvoted如此upvote它找到别人很容易。你可以发布你的var_dump()和数据库记录,以便我可以更多地了解你的问题 –