在我的數據庫中,我有兩個表notification
和alertFrequency
。通知的字段爲id and website_url
,警報頻率爲id
和notification_id
。兩張表都有一對多的模型。通知可以有一個或多個alertFrequency
。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);
}
}
在通知模型中,我寫了一個名爲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;
}
這是一個正確的方式來提取數據?我將不勝感激任何建議和幫助?
我認爲這並沒有太大的差別。我也會檢查它。 tnx –
我應該在哪裏寫這段代碼,或者替換我的舊代碼。 –
$ alert_frequency = AlertFrequency :: with('notification') - > orderBy('created_at','desc') - > first(); –