Laravel does not return BelongsTo

0

Oops I have two tables one with a Product name and one with a ProductName name. When I make the relationships in models, only the ProductCategory object returns the products, the Product object does not return the 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 does not.

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

Returns null.

    
asked by anonymous 13.07.2016 / 03:50

1 answer

0

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

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 Product template and create a relationship with the ProductCategory template,% the column belongsTo to make this relation.

I suggest reading the related page on official documentation , the exact topic is product_category_id .

    
13.07.2016 / 15:39