How to do inner join within Auth in laravel 5.3

2

In the default migration that Laravel brings to use Auth , I made a ForeignKey with another table by calling the ID. For better understanding I 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 {{ Auth::user()->planta_id }} method it prints the table id plants, I wanted to use INNER JOIN to print Nome and not id , but I do not know where to do this .

    
asked by anonymous 29.09.2016 / 17:36

1 answer

2

You need to set the two models with the 1:N ( 1 to 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 get the name from planta :

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

Note: Put the field name in lowercase and if compound is separated by underscore , default nomenclature for development. Nothing prevents it from being otherwise, but, it becomes more readable when it comes to with

I did not pay attention to the names of the fields, because the part of the model User !

Link: One To Many

    
29.09.2016 / 17:52