2017-01-16 2 views
1

В моей базе данных у меня есть две таблицы notification и alertFrequency. Уведомление имеет поле id and website_url, а частота оповещения имеет id и notification_id. Обе таблицы имеют модели, которые являются одними для многих. Уведомление может содержать один или несколько alertFrequency.one to many relationship in laravel

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); 
    } 
} 

в модели уведомлений, я написал функцию, называемое оповещением, которая даст мне laastest сигнал оповещения, связанное с конкретным 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(); 

загружает последние AlertFrequency вместе с его notification.

См. One to Many relationship и Eager loading в документации.

+0

я думал, что это не имеет большого значения. я также проверю его. tnx –

+0

где я должен писать этот код или заменить старый код. –

+0

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

0

, чтобы получить оповещение о славе, связанное с конкретной веб-страницей с URL-адресом $ website_url.

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

hasMany отношение:

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