laravel中的一对多关系

问题描述:

在我的数据库中,我有两个表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; 
} 

这是一个正确的方式来提取数据?我将不胜感激任何建议和帮助?

通知的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(); –

可以通过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'); 
    }