Relationship One for An Laravel

Asked

Viewed 1,147 times

1

Good morning, I’m developing my first project in Lisbon, and I’m having a hard time in the relationship of two entities.

Modelo do banco

I have my student registration, but I’m not able to understand how to call the cursofac through a dropdown in student registration.

2 answers

1

So,

I think you will get a little extra work by not following the patterns of column names and table names. That by default should be:

  • tables: plural
  • Primary key: id
  • Foreign key: table name in singular concatenated with '_id'

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

Database

cursos          alunos
  id              id
  nome            curso_id
                  nome

Models taking into account that you are using Standard 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, take a look at the documentation because it’s better explained.

http://laravel.com/docs/5.1/eloquent-relationships#Defining-relationships

  • Thanks Walmir Neto, but as I’m starting I’m having a hard time knowing how to work this in the view. When registering the student as I can call it coming from the entity course. And relation the entities they are plural. Thank you

0

Don’t worry!

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

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

http://laravel.com/docs/5.1/eloquent-relationships#one-to-one

Browser other questions tagged

You are not signed in. Login or sign up in order to post.