Search code examples
phplaravellaravel-5.3

One to many relationship use attach or save


I have two tables called notification and alerFrequencies table, and they have ont to many relationship respectively. the notification_id is a foreign key in the alertFrequencies table. the notification table has id and website URL fields and the alerFrequncies table has id, notification_id and created_at fields.

I am trying to insert data automatically into the alertFrequencies table using the following function, but failed to do so, it complained about the attach function?

private function add(Notification $notification,alertFrequency $alert, $alertTime){
    $notification->alertFrequencies()->attach($alert,
                            ['created_at'=>date($alertTime)]);
}

Solution

  • Use update() instead of attach() since it is one to many relation. Attach used in many to many ralations

    private function add(Notification $notification,alertFrequency $alert, $alertTime){ 
        $notification->alertFrequencies()->update(['created_at'=>date($alertTime)]); 
    }
    

    Edit---

    To answer your comment register created_at and updated_at field in $dates array in your Notification model like this.

    protected $dates = [
        'created_at',
        'updated_at'
    ];
    

    And when you saving your data as follows using Carbon

        $notification->alertFrequencies()->update(['created_at'=>Carbon::parse($alertTime)]);