PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 16, 2022

[FIXED] How to eager load only 1 result from many to many relationship Laravel

 November 16, 2022     eloquent, laravel, laravel-6     No comments   

Issue

How can I eager load only one from many to many relationship?

I have two models Application & Applicant

Models\Application.php

public function applicants() {
    return $this->belongsToMany(Applicant::class);
}

public function oneApplicant() {
    return $this->applicants()->first();
}

I'm wanted to paginate on the applications and want to load only one applicant (if they have.)

return Application::stage( $stages )
->stagenot($stageNot)
->refered( $refered, $term )
->with(['oneApplicant'])
->orderBy('created_at','desc')->paginate( $count );

But it isn't working. Getting the first result like this return $this->applicants()->first() will produce an error Call to undefined method Illuminate\Database\Query\Builder::with()

If I also put a limit instead of first return $this->applicants()->limit(1) it will only show one applicant to the last collection.

I also tried to modify the query directly on eager loading call to get the first row

return Application::with(['applicants',  => function( $query ) {
        $q->first();
    }])->orderBy('created_at','desc')->paginate( $count );

But the result is the same as adding a limit(1) on directly on the relation, it will only add one applicant to the last item from collection and the other item have empty array value

Can anybody help :)

Thanks


Solution

I realized its too complex to achieve it myself and ended up using the eloquent-eager-limit package from staudenmeir (big thanks to him, save me hours of work :) )

here's my model

class Application extends BaseModel {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;

    public function applicants() {
        return $this->belongsToMany(Applicant::class);
    }

    public function oneApplicant() {
        return $this->applicants()->limit(1);
    }
}

Then I was able to use it on my controller

return Application::stage( $stages )
    ->stagenot($stageNot)
    ->refered( $refered, $term )
    ->with([
        'oneApplicant',
        'oneApplicant.onePhone:model_id,number',
        'oneApplicant.oneAddress:model_id,state'
    ])->orderBy('created_at','desc')->paginate( $count );



Answered By - SymmetricsWeb
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing