【发布时间】:2017-01-18 10:10:18
【问题描述】:
我在数据库中有一对多的关系,我正在尝试提取最新的。表名是notification 和alertFrequency,它们都有各自的模型。我想编写一个查询,它将获取与通知表中特定网站相关联的最新时间戳。 alertFequency 表只有两列,即notification_id 和created_at。以下是我的模型通知模型
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 添加.....抱歉,我不知道如何在此处发布数据库。
【问题讨论】:
-
您只是在“选择”
created_at。所以它只返回它。您可以尝试在 select() 中添加您想要的字段或更好地解释您要实现的目标吗? -
我想要实现的是,当在通知表中添加新网站时,新网站的notification_id 将添加到alertFrequency 表中,并带有created_at 时间戳,可能有很多通知表中添加的网站,其notification_id是alerFrequency表中的外键,那么我想提取特定网站的最新created_at。
标签: php laravel laravel-5.3