mercredi 25 mai 2016

Eloquent eager load constrain by parent column values

I'm on Laravel 5.2 and I'm having a problem using Eloquent to retrieve data with eagerly loaded relationships which need to be constrained by values from other relations. I'm not sure of the proper term for this relation pattern and thus it's been difficult to locate a solution to this.

I will simplify the table/model names for clarity:

Three tables/models: E, D, and M.

Relations: D belongsTo E, M belongsto E, E hasMany D, and E hasMany M.

What I want

I want a listing of D, with E and then M eagerly loaded into the properties of the D objects such that $D->E->M is a listing of M belonging to that E, which in turn D belongs to.

The problem is I need the eager loading for M to be constrained by values from columns on D.

Example:

$D = \App\D::with(['E' => function($query) {

  $query->with(['M' => function($query) {

    //example of what I'd like to do (but doesn't work)
    $query->where('start_timestamp','>=','D.start_timestamp'); 

  }]);

}])->get();

In that example, it attempts to compare M's start_timestamp field to the string 'D.start_timestamp', instead of D's start_timestamp value.

Question

Is it possible to accomplish constraining an eager load by earlier related column values? If so, how?

I have tried...

...using $query->whereRaw to explicitly reference the earlier table's columns

$query->whereRaw('M.start_timestamp >= D.start_timestamp')

but this errors out with 'D.start_timestamp' as an unknown column.

...using whereColumn, but this doesn't seem to work with eager loading constraints (errors out with unknown column 'column').


I am trying to solve this problem in the "Eloquent way", avoiding the use of raw SQL and joins. I know how to solve this via SQL and joins but I'd rather avoid it if possible.

Any help you can offer would be appreciated, thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1sQXj6Q
via IFTTT

Aucun commentaire:

Enregistrer un commentaire