Home » Php » Issue Laravel Relationships

Issue Laravel Relationships

Posted by: admin October 20, 2018 Leave a comment

Questions:

I have two tables users and notes and I’m trying to relate to them a certain way but when I am created my hasMany and belongTo the script does not load and times out after a certain amount of time.

I am trying to create a basic note-adding system so that you can add notes onto a user’s account. I have successfully established a hasMany relationship to users who have notes on their account, however, I’m trying to define a relationship on notes where it brings through the user who has created the note.

My database is laid out like so:

Users:

`id`, `username`, `password`

1   , Connor    , hash

Notes:

`id`, `note`, `user_id`, `user_id_created`

1   , Hello ,  1       , 1

So this means that user ID 1 has created a note against themself, so in my User model I use:

class User { 
    public function notes(){
        return $this->hasMany("App\Note");
    }
    public function created_notes(){
        return $this->hasMany("App\Note", "id", "user_id_created");
    }
}

And then in my Notes model I use:

class Note {
    protected $with = ['created_by']
    public function created_by(){
        return $this->belongsTo("App\User", "user_id_created", "id");
    }
}

However, when I’ve done this, and try and use $with = ['created_by'] on my Note’s model, the script crashes and doesn’t load at all.

Can anyone shed some light on this?

Answers: