Laravel does not return Belongsto

Asked

Viewed 418 times

0

Opa galera I have two tables one with name Product and another with name Productocategoria. When I go to make the relationship in the models, only the Product object returns the products, the Product object does not return category.

 class ProdutoCateg extends Model
{
    public function produtos(){
        return $this->hasMany('app\Produto');
    }
}



class Produto extends Model
{
    public function categoria(){
        return $this->belongsTo('app\ProdutoCateg');
    }
}


class Fktables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('produtos', function ($table){
            $table->foreign('id_produto_categs')->references('id')->on('produto_categs');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

If I do

use app\ProdutoCateg; 
$c = ProdutoCateg::find(1);
$c->produtos;

It works now if it’s the other way around.

use app\Produto
$c = Produto::find(1);
$c->categoria;

Returns null.

1 answer

0


In this case you need to explicitly specify the foreign key in the relation, thus:

class Produto extends Model
{
    public function categoria(){
        return $this->belongsTo('app\ProdutoCateg', 'id_produto_categs');
    }
}

I recommend that you use the exact names to follow the conventions that Laravel uses, for example, if you have a model Product and creates a relationship with the model ProductCategory of the kind belongsTo, Laravel automatically uses the column product_category_id to make that relationship.

I suggest reading the related page on official documentation, the exact topic is Defining The Inverse Of The Relation.

  • 1

    Vlw worked out well!!

  • Good that I helped @Guilhermecosta, you can signal as accepted answer if this is the case. Hugs.

Browser other questions tagged

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