How to create the relationship of two tables in laravel lumen?

4

I have two tables attached so that

In my project Laravel what would be the relationship that I would have to put in the model

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Archivo extends Model
{

protected $fillable = [
        'ruta',
    ];

}
    
asked by ortiga 24.02.2018 в 17:25
source

1 answer

4

The relationships here are defined One to many (hasMany) and in reverse form belongsTo so from the file you can get to user belongs to you.

Model User

public function archivos()
{
    return $this->hasMany('App\Archivo');
}

Model File

public function usuario()
{
    return $this->belongsTo('App\User');
}

If you have problems with belongsTo (you may not) you can specify the columns of your foreign key of your model with respect to User

public function usuario()
{
    return $this->belongsTo('App\User','user_id');
}

And when you want to obtain for example the files of a user it would be

$usuario = User::find(1);
$archivos = $usuario->archivos;
dd($archivos);

And if you want to get the User from a file

$archivo = Archivo::find(1);
dd($archivo->usuario);
    
answered by 24.02.2018 / 17:31
source