vincent15000's avatar

Relationship with pivot table

Hello,

I have a pivot table with some additional datas.

While declaring the pivot additional datas, I don't want to load the formula.

public function articles(): BelongsToMany
{
    return $this->belongsToMany(Article::class, 'group_article')->using(GroupArticle::class)->withPivot('rounding_rule', 'precision');
}

I prefer loading the formula only when needed.

$table->loadMissing([
    'groups.articles' => function ($q) {
        $q->withPivot('formula', 'rounding_rule', 'precision');
    }
]);

But it doesn't work like this.

Is there another way to do that ?

Sure I can retrieve the data with a raw query, but I'm trying to do that with the query builder.

Thanks for your help.

V

0 likes
2 replies
Shivamyadav's avatar
Level 20

Here is the key thing...

// Searched on Google and got this load missing() used case.

Laravel's loadMissing() method is used to eager load a relationship on a model or a collection of models only if that relationship has not already been loaded.

  1. withPivot() only applies when the relationship is loaded for the first time.

  2. If groups.articles was already loaded earlier without the formula column, loadMissing() will not re-query or add new pivot fields.

  3. Eloquent treats the relationship as already loaded, so this behavior fails silently by design.

I think you can define the 2 relationship one for without formula and other with formula

Like this ..

//Without formula relationship 
public function articles(): BelongsToMany
{
    return $this->belongsToMany(Article::class, 'group_article')
        ->using(GroupArticle::class)
        ->withPivot('rounding_rule', 'precision');
}

// With formula needed 
public function articlesWithFormula(): BelongsToMany
{
    return $this->belongsToMany(Article::class, 'group_article')
        ->using(GroupArticle::class)
        ->withPivot('formula', 'rounding_rule', 'precision');
}
1 like
vincent15000's avatar

That's ok for me, effectively I know that, but it's stupid of me, I didn't realize that I used loadMissing instead of load().

Please or to participate in this conversation.