1

I have tried to get only two image by using eloquent model like this

$data = Wedding::with(['weddingimage'=>function($q)use($req){
    $q->where('is_cover',0)
       ->limit(2);
    }])->withCount('weddingimage')
        ->limit(2)
        ->get();

but get only two images in first loop means index 0 and not in next index means 1,2. please help me out. Thanks in advance

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Shaddy
  • 49
  • 1
  • 1
  • 7
  • 1
    btw, if you add a limit in the eager load it will only limit the entire set of records it finds for the relationship in total for all parents ... so 2 in total, not 2 per parent – lagbox Dec 07 '21 at 15:47
  • so , how can i get only two with per parent – Shaddy Dec 07 '21 at 15:50
  • @Shaddy see my answer for how to limit 2 per-parent (instead of 2 in total). – Top-Master Dec 07 '21 at 18:20

1 Answers1

-1

Laraval does not have this feature built-in.

If you add a limit in the relationship's eager-loading, it will only limit the total set of records it finds, 2 for all parents, not 2 per parent, while even the first parent may have more than 2 images.

But don't worry, Jonas Staudenmeir toke his time developing the missing per-parent limit, see: https://github.com/staudenmeir/eloquent-eager-limit

Usage:

You need to apply trait to both your models, in your case the models may look like:

class WeddingImage extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Wedding extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;

    public function weddingimage() {
        return $this->hasMany(WeddingImage::class);
    }
}

Then simply chain ->limit(2) in your eager-load query (which seems you already do).

Top-Master
  • 7,611
  • 5
  • 39
  • 71