Relationship one to one Laravel

1

Good morning, I'm developing my first project in laravel, and I'm having a difficult relationship in two entities.

I have my student registration, but I can not understand how to call coursefac through a dropdown in the student record.

    
asked by anonymous 20.10.2015 / 14:25

2 answers

1

So,

I think you're going to get a little extra work by not following the table name and column names. Which by default should be:

  • tables: plural
  • primary key: id
  • foreign key: name of the table in the singular concatenated with '_id'

Case: A course has several students and a student belongs to a course.

Database

cursos          alunos
  id              id
  nome            curso_id
                  nome

Models taking into account that you are using laravel 5.1


class Curso extends Model
{
    public function alunos()
    {
        return $this->hasMany('App\Aluno');
    }
}

class Aluno extends Model
{
    public function curso()
    {
        return $this->belongsTo('App\Curso');
    }
}

Well that's it, read the documentation as it is better explained.

link

    
20.10.2015 / 16:30
0

Do not worry!

In your model, declare the method according to Answer 1 above, but pass the fields of your tables involved in the relationship as a parameter.

class Curso extends Model
{
    public function alunos()
    {
        return $this->hasMany('App\Aluno', 'foreign_key', 'local_key');
    }
}

link

    
20.10.2015 / 23:06