Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent

Hi,

I want to retrieve a list of results from a model, what I am trying is:

App\Score::with( array('cycle' => function($query){ $query->select('id', 'name', 'starts', 'ends')->where( DB::raw('YEAR(starts)'), '=', '2016'); }) )->get();

This will return all Sectors with its given Dependencies each dependency has a Score and this Scores are assign through Cycles, each cycle has a starts and ends field, so I want to get all the Scores that are in the Cycles that starts in 2016, the thing is with this Eloquent query I am getting all the desire data plus the non-desire data which is Scores that has the cycle ::with has null, is there a way to remove it?

When I try:

App\Score::with( array('cycle' => function($query){ $query->select('id', 'name', 'starts', 'ends')->where( DB::raw('YEAR(starts)'), '=', '2016'); }) )->whereNotNull('cycles')->get();

It will prompt there is no 'cycle' field. Any help greatly appreciated, thanks.

Last updated 3 years ago.
0

You are checking the existence of a relationship? use whereHas.

0

Could you elaborate a little bit more on that? I believe is a relationship between Score and Cycle, so far I do have a field in Score which is cycle_id, I have in Scores a relationship with Dependencies, could I have two or more to different models entities?

0

I manage to make it work using a JOIN but now its not getting the Prizes information, any ideas?

App\Sector::with( array('dependencies' => function($query) { $query->with( array('scores' => function($query){	$query->join('cycles', 'scores.cycle_id', '=', 'cycles.id')->where( DB::raw('YEAR(cycles.starts)'), '=', '2016')->with('prizes'); }) ); }) )->get();
0

Sign in to participate in this thread!

Eventy

Your banner here too?

JWBrownie jwbrownie Joined 1 Mar 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.