Relationship problems one for many

Asked

Viewed 2,227 times

4

I’m trying to create a CRUD simple category and subcategory registration where a category may have several subcategories but a subcategory may have only one category. On my migrátion I made my tables as follows:

Schema::create('sub_categorias', function (Blueprint $table) {
   $table->increments('CdSubCategoria');
   $table->integer('CdCategoria')->unsigned()->index();
   $table->string('NmSubCategoria');
   $table->string('DscSubCategoria');
   $table->integer('FlgPontua');
   $table->integer('QtdPontos');
   $table->integer('MaxPontosPorSubCategoria');

   $table->timestamps();
   $table->softDeletes();



    $table->foreign('CdCategoria')
          ->references('CdCategoria')
          ->on('categorias');
});

And my table of categories:

Schema::create('categorias', function (Blueprint $table) {
   $table->increments('CdCategoria');
   $table->string('NmCategoria', '50');
   $table->string('DscCategoria', '255');
   $table->timestamps();
   $table->softDeletes();

});

Already in my category model I made:

use SoftDeletes;

protected $fillable = ['CdCategoria','NmSubCategoria', 'DscSubCategoria', 'FlgPontua', 'QtdPontos', 'MaxPontosCategoria'];
protected $primaryKey = 'CdSubCategoria';
protected $dates = ['deleted_at'];

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

And in the subcategories:

use SoftDeletes;

protected $fillable = ['NmCategoria', 'DscCategoria'];
protected $primaryKey = 'CdCategoria';
protected $dates = ['deleted_at'];

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

With all this done my controller sends to a lisSubCategories view, where I want to list the subcategories and show the name of her parent category, in this way:

$subCategoria->categoria->NmCategoria

When performing this command together with dd() is returned to me the error page describing the error:

Trying to get Property of non-object (View: ... views Subcategory listSubCategory.blade.php)

1 answer

7


In the Eloquent, there is a pattern in the relationship keys, which is not mandatory, which is a convention of nome de tabela, underscore and chave, example: categoria_id.

How not was followed and is not mandatory, mainly by legacy banks, the Eloquent can be configured with field names in its own way, only this implies informing the Eloquent what are the keys and name of fields.

Translation

1:1

$this->hasOne(relacao, chave estrangeira, primary key);

N:1

$this->belongsTo(relação, chave estrangeira local, primary key da relação); 

1:N

$this->hasMany(relação, chave estrangeira da relação, primary key local);

N:N

$this->belongsToMany('relacao', 'nome da tabela pivot', 'key ref. local model em pivot', 'key ref. relação em pivot')

This was all just the introduction to solving the question problem, so reconfiguring the relationships as explained does not follow the convention needs to be specified in your Eloquent Model.

use SoftDeletes;

protected $fillable = [
          'CdCategoria',
          'NmSubCategoria',
          'DscSubCategoria', 
          'FlgPontua', 
          'QtdPontos', 
          'MaxPontosCategoria'
      ];

protected $primaryKey = 'CdSubCategoria';

protected $dates = ['deleted_at'];

public function categoria()
{
    return $this->belongsTo('App\Categoria','CdCategoria','CdCategoria');
}

use SoftDeletes;

protected $fillable = ['NmCategoria', 'DscCategoria'];

protected $primaryKey = 'CdCategoria';

protected $dates = ['deleted_at'];

public function subCategoria()
{
    return $this->hasMany('App\SubCategoria','CdCategoria','CdCategoria');
}

In your specific case it became easy to relate, often the keys have different names and cause extra work in configuration and maintenance of code.

To find the relationship information use with('name_relationship->method name') to load eager loaded of the relationship:

Example:

$subCategoria = SubCategoria::with('categoria')->get();

and this summarizes in the code below that needs to be executed:

$subCategoria->categoria->NmCategoria
  • 1

    You are great ! Congratulations

Browser other questions tagged

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