wivku
wivku

Reputation: 2663

Eloquent query for DB query with multiple joins

My simplified Model relationships:

User (id, email) → Timeline (id, user_id) → Activity (id, timeline_id) → Trackpoint(id, activity_id)

Q1: How do I get Trackpoints for a specific user and date range?
Q2: How do I get the Timeline for a certain Trackpoint?

I currently use a DB query for Q1, but was hoping there was a more... Eloquent way.

        $trackpoints = DB::table('trackpoints')
            ->join('activities', 'activities.id', '=', 'trackpoints.activity_id')
            ->join('timelines', 'timelines.id', '=', 'activities.timeline_id')
            ->where('timelines.user_id', 1)
            ->whereBetween('trackpoints.timestamp',['2019-12-13','2019-12-16'])

Or does that require e.g. https://github.com/staudenmeir/belongs-to-through ?

Upvotes: 0

Views: 136

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

In the first case, Laravel has no native support for a direct relationship. You can use one of my other packages: https://github.com/staudenmeir/eloquent-has-many-deep

class User extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function trackpoints()
    {
        return $this->hasManyDeep(
            Trackpoint::class, [Timeline::class, Activity::class]
        );
    }
}

$trackpoints = User::find($id)->trackpoints()
    ->whereBetween('trackpoints.timestamp', ['2019-12-13','2019-12-16'])
    ->get();

For the second query, you can use the belongs-to-through package you mentioned:

class Trackpoint extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;

    public function timeline()
    {
        return $this->belongsToThrough(Timeline::class, Activity::class);
    }
}

$timeline = Trackpoint($id)->timeline;

In Laravel 5.8+, you can also use a native HasOneThrough relationship:

class Trackpoint extends Model
{
    public function timeline()
    {
        return $this->hasOneThrough(
            Timeline::class, Activity::class,
            'id', 'id',
            'activity_id', 'timeline_id'
        );
    }
}

$timeline = Trackpoint($id)->timeline;

Upvotes: 1

Related Questions