laravel中的一对多关系未能保存

时间:2017-01-20 11:00:56

标签: php laravel laravel-5.3

我在通知表和alerFrequency表之间有一对多的关系。所有模型都运行正常,唯一遗漏的是以下内容。 alertFrequency表中记录在通知表中的特定网站的时间戳用于计算经过时间,然后确定是否发送通知,以及将新记录插入到alertfrequency表中。我有一个叫做guzzle控制器的控制器类。名为add的函数是为了做到这一点但是失败了,但我有一个名为addToNotification的函数,它将vales附加到数据透视表中并且运行正常。我会很感激你的建议和帮助吗?

private function addStatusToNotification(Notification $notification, Status $status, $resCode)    {
    $notification->statuses()->attach($status, [
        'values' => strval($resCode)
    ]);
}

/*function to add new time stamp into the alertFrequency table*/
private function add(Notification $notification, AlertFrequency $alertTime){
    $notification->alertFrequencies()->save($alertTime);
}

private function sendNotification(Notification $notification, $status_health, $alert_frequency, $resCode,$alertTime, AlertFrequency $alert)    {       
    // If this is the first time we check, OR if the status changed from up to down and vice versa, notify!!!
    if (empty($status_health['timestamp']) || Notification::health($resCode) <> Notification::health($status_health['value'])){
        $this->report($notification,$resCode);
        return;
    }
    // If the website is (still) down and the alert frequency is exceeded, notify!!!
    if(Notification::health($resCode) === 'down' && \Carbon\Carbon::parse($alertTime)->diffInMinutes() >= $alert_frequency){            
        $this->report($notification,$resCode);
       //expected to save the new record in the alertFrequencies table but failed to do so
        $this->add($notification,$alert);
    }
}

public function status()
{
    $notifications = Notification::where('active', 1)->get();

    $alert = AlertFrequency::with('notification')->first();

    $status = Status::where('name', 'health')->first();

    foreach ($notifications as $notification) {
        $this->updateStatus($notification, $status,$alert);
    }  
}

private function updateStatus(Notification $notification, Status $status, AlertFrequency $alert)
{
    $status_health = $notification->status('health');
    $check = empty($status_health['timestamp']);
    $elapsed_time = $check ? 10000 : \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes();

    $check_frequency = $this->getCheckFrequency($notification);       
    /* create an attachemtn in to the alerFrequenct table*/        
    $alertTime = $notification->getLastTimestampAttribute();     

    if ($check || $elapsed_time >= $check_frequency) {
        $resCode = $this->getStatusCode($notification->website_url);
        $this->addStatusToNotification($notification, $status, $resCode);
        $this->sendNotification(
            $notification,
            $status_health,
            $this->getAlertFrequency($notification),
            $resCode,
            $alertTime,
            $alert
        );            
    }
}

0 个答案:

没有答案