2017-01-16 78 views
1

在我的數據庫中,我有兩個表notificationalertFrequency。通知的字段爲id and website_url,警報頻率爲idnotification_id。兩張表都有一對多的模型。通知可以有一個或多個alertFrequencylaravel中的一對多關係

class Notification extends Model { 
    public function alertFrequencies() { 
     return $this - > belongsToMany('AlertFrequency::class'); 
    } 
} 

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

在通知模型中,我寫了一個名爲alert的函數,它會給我一個與特定websie相關的最新警報。

public function alert(){ 
    $alert_frequency = AlertFrequency::find('notification_id')->first(); 
    $o_notification = $this->alertFrequencies()->where('notification_id',$alert_frequency->id) 
       ->select('created_at')->orderBy('created_at')->first(); 
    if($alert_frequency ==null){ 
     return false; 
    } 
    return created_at; 
} 

這是一個正確的方式來提取數據?我將不勝感激任何建議和幫助?

回答

0

通知的hasMany AlertFrequency

public function alertFrequencies(){ 
       return $this->hasMany('App\AlertFrequency'); 
     } 

,並

$alert_frequency = AlertFrequency::with('notification')->orderBy('created_at','desc')->first(); 

負荷與它的notification沿最新AlertFrequency

請參閱One to Many relationshipEager loading的文檔。

+0

我認爲這並沒有太大的差別。我也會檢查它。 tnx –

+0

我應該在哪裏寫這段代碼,或者替換我的舊代碼。 –

+0

$ alert_frequency = AlertFrequency :: with('notification') - > orderBy('created_at','desc') - > first(); –

0

可以通過url $ website_url獲得與特定websie相關的最新警報。

Notification::where('website_url', $website_url)->orderBy('created_at')->first(); 

的hasMany關係:

public function alertFrequencies(){ 
      return $this->hasMany('App\AlertFrequency','notification_id'); 
    }