Auto Relationship Laravel
1) the migration corresponding to this table?
To create the file ( the blank template ) in console
do:
php artisan make:migration Grupo
Configuring:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Grupo extends Migration
{
public function up()
{
Schema::create('grupo', function (Blueprint $table)
{
$table->increments('id');
$table->string('description', 50);
$table->integer("grupoid", false, true)
->nullable();
$table->index("grupoid");
$table->foreign("grupoid")
->references('id')
->on('grupo');
});
}
public function down()
{
Schema::drop('grupo');
}
}
Generate Table:
php artisan migrate
2) creating the Eloquent model with the relationship?
To create the file ( the blank template ) in console
do:
php artisan make:model Grupo
Configuring:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Grupo extends Model
{
protected $primaryKey = "id";
protected $fillable = array('description','grupoid');
protected $table = "grupo";
public $timestamps = false;
//relacionamento (auto-relacionamento) item 4
public function grupos()
{
return $this->hasMany(Grupo::class, 'grupoid', 'id');
}
// um técnica do item 3
public function isFather()
{
return is_null($this->attributes['grupoid']);
}
// aqui seria o item 3
protected $appends = ['is_father'];
public function getIsFatherAttribute()
{
return is_null($this->attributes['grupoid']);
}
}
3) How would you know if a given id is Father, any technique?
In the 2) item, two techniques were created:
- One would be to create a method and compare if the
grupoid
is null
(is_null)
and the isFather()
method was created:
public function isFather()
{
return is_null($this->attributes['grupoid']);
}
- But with method only it does not come out in the results of
Array
or Json
, so we'll create a appends
in that Model Grupo
:
protected $appends = ['is_father'];
public function getIsFatherAttribute()
{
return is_null($this->attributes['grupoid']);
}
resulting in the format JSON
:
{"id":4,"description":"Grupo 2","grupoid":null,"is_father":true,"grupos":[]}
4) if id is Parent how to load children into relationships?
Simply with the command with
:
$grupo = App\Models\Grupo();
$grupo->with('grupos')->find(4);