0

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 ?

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Will check out your package. For Q2: I thought I could use hasOneThrough with just the first 2 arguments. Apparently not! FYI: argument 5 and 6 are not necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.