How to make Inner Join inside the Auth in Laravel 5.3

Asked

Viewed 281 times

2

In the Migration standard that Laravel brings to use the Auth, made a Foreignkey with another table linking by ID. For better understanding put here the tables and with the following columns:

Plants (table)

 ID | Nome (colunas)

Users (table created by Auth)

ID | User | planta_id

Using the method {{ Auth::user()->planta_id }} he prints the table id plants, wanted to use the INNER JOIN to print the Nome and not the id, but I don’t know where to do it.

  • you have the models of these two tables and relations ready? if you have the model you can ask the question?

  • I do have to put

1 answer

2


You need to configure both models with the relationship of 1:N (1 for many):

Plants

class Plantas extends Model
{
    protected $primaryKey = "ID";
    protected $fillable = array('Nome');
    protected $table = "plantas";
    public $timestamps = false;
    public function users()
    {     
        return $this->hasMany('App\Users', 'planta_id', 'ID');
    }
}

Users

class Users extends Model
{
    protected $primaryKey = "ID";
    protected $fillable = array('Nome','planta_id');
    protected $table = "users";
    public $timestamps = false;
    public function planta()
    {     
        return $this->belongsTo('App\Plantas', 'planta_id', 'ID');
    }
}

To catch the name of planta:

{{ Auth::user()->planta()->Nome }}

Observing: put the name of the fields in lowercase and if it is composed separately by underscore, standard nomenclature for development. Nothing prevents it from being otherwise, but it is more readable when it comes to with

I did not notice the names of the fields, because the part of the model User!

Link: One To Many

  • 1

    That’s exactly what I wanted, I didn’t know how I would have to use hasMany in this case of Auth. Opened my mind, thank you.

  • of plant for user is hasMany the opposite is belongsTo pay attention to this ...

  • 1

    That’s right, you helped me a lot, now I can manage more easily with the https://laravel.com/docs/5.3/eloquent-relationships#one-to-Many documentation thank you very much.

Browser other questions tagged

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