2017-01-16 14 views
1

私のデータベースでは、私はnotificationalertFrequencyという2つのテーブルを持っています。通知にはフィールドid and website_urlがあり、警告頻度はidnotification_idです。どちらの表にも1対多のモデルがあります。通知には、1つまたは複数のalertFrequencyを含めることができます。laravelの1対多の関係

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( '通知') - > 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'); 
    }