laravel中的一对多关系

时间:2017-01-16 09:14:18

标签: php laravel

在我的数据库中,我有两个表notificationalertFrequency。通知的字段为id and website_url,提醒频率为idnotification_id。两个表都有一对多的模型。通知可以有一个或多个alertFrequency

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的函数,它会给我一个与特定网站相关的最新警报。

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

这是提取数据的正确方法吗?我会很感激任何建议和帮助吗?

2 个答案:

答案 0 :(得分: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 relationshipEager loading

答案 1 :(得分:0)

使用url $ website_url获取与特定网站相关联的最新警报。

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

hasMany relation:

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