Additional Fields in Pivot Model Laravel 6?

Asked

Viewed 144 times

1

I’m in my first Laravel Framework project and I’m having difficulty in relationship N:M, I have the database structure fornecedor->fornecedor_produto->produto**

have my models:

class Fornecedor extends Model{
    public function produtos()
    {
        return $this->belongsToMany(Produto::class)
            ->using(FornecedorProduto::class);
    }
}

class Produto extends Model{
    public function fornecedores()
    {
        return $this->belongsToMany(Fornecedor::class)
            ->using(FornecedorProduto::class);
    }
}

class FornecedorProduto extends Pivot {}

my difficulty is that my table Pivot(fornecedor_produto) has 32 fields beyond the produto_id and fornecedor_id;

When I use the $fornecedor->produtos()->first()->pivot, returns me only

#attributes: array:2 [
    "fornecedor_id" => 1
    "produto_id"    => 1
]

Got a way to return mine 32 other fields without putting all fields in the withPivot([col1,col2,...,col32]) in relationships?

1 answer

1


has how to return my 32 other fields without putting all fields in withPivot([col1,col2,...,col32]) in relationships?

The answer the documentation has is NAY, that is to say, all extra (additional) fields must be explicitly passed in the relation as suggested in the example:

return $this->belongsToMany('App\User')
            ->using('App\RoleUser')
            ->withPivot([
                'created_by', // campo extra
                'updated_by', // campo extra
             ]);

Code reference: Defining Custom Intermediate Table Models

or separated by comma:

return $this->belongsToMany('App\Role')->withPivot('column1','column2');

Code reference: Retrieving Intermediate Table Columns

It is also good to clarify that the and their relationships taking out the conventions part the rest everything needs to be configured and the table Pivot when leaving the convention you need the extra fields to be declared, so that framework know what you need to return and also at the time of recording operations and/or change what to do.

If it were done in the traditional way would not all fields be passed? The answer is yes, so it follows the same planning even being a ORM.

  • 1

    thanks for the clarification, I thought I would have some Trick to declare these fields in the model pivot.

  • @Virgilionovic Did laps all, no need to pass withPivot to the Created and Updated only if case involves more data.

  • I took a negative vote for harassment so of course.

Browser other questions tagged

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