在我的数据库中,我有两个表notification
和alertFrequency
。通知的字段为id and website_url
,提醒频率为id
和notification_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;
}
这是提取数据的正确方法吗?我会很感激任何建议和帮助吗?
答案 0 :(得分:0)
通知hasMany AlertFrequency
public function alertFrequencies(){
return $this->hasMany('App\AlertFrequency');
}
和,
$alert_frequency = AlertFrequency::with('notification')->orderBy('created_at','desc')->first();
加载最新的AlertFrequency
及其notification
。
答案 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');
}