我在数据库中有一对多的关系,我试图提取最新的。表格名称为notification
和alertFrequency
,它们各自具有模型。我想编写一个查询,以便获取与通知表中特定网站关联的最新时间戳记。 alertFequency
表只有2列,即notification_id
和created_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 .....对不起,我不知道我可以如何发布数据库在这里。
你只是'选择''created_at'。所以它只返回它。你可以尝试在select()中添加你想要的字段,或者更好地解释你想实现的目标吗? – EddyTheDove
我想要实现的是,当通知表中添加新网站时,新网站的notification_id将被添加到带有created_at时间戳的alertFrequency表中,并且可能会在通知表中添加许多网站,他们的notification_id是alerFrequency表中的外键,然后我想提取特定网站的最新created_at。 –