1

I'm trying to list all runs where a user has a TIME (think of runs as races). A user won't always run, so won't always have a time.

Everything is working great apart from this one part which I've yet to get my head around after looking through the docs.

At the moment I'm trying the following but it does not produce any users, just an empty array:

$runs = Run::with('times')->where('user_id', $user->id)->get();

Is there something I'm missing here? Here is my database structure and Model relationships:

Database structure at present:


USERS:

id

name


RUNS:

id

name


TIMES:

id

time

user_id

run_id


The Models:

USER:

public function times()
{
    return $this->hasMany(Time::class);
}

RUN:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Run extends Model
{    
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function times()
    {
        return $this->hasMany(Time::class);
    }
}

TIME:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Time extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function run()
    {
        return $this->belongsTo(Run::class);
    }

}
3
  • 1
    Does the Run model have a user_id column? How are you establish a relationship between run and user without a foreign key?
    – Alec Joy
    Dec 18, 2019 at 20:08
  • The run model doesn't have one. In my mind - the user isn't associated with the run, only a time (which contains the run_id). Dec 18, 2019 at 20:22
  • 1
    Okay, then I believe the relationship you want for User->run and vice versa would be a hasManyThough, not a belongsTo. I will add that to my answer, it doesn't change my answer but it will may help you in the future.
    – Alec Joy
    Dec 18, 2019 at 20:25

2 Answers 2

3

Run doesn't have a user_id column, and I believe a whereHas is what you want here as you are trying to only get runs where a certain user has a time not all runs with only the times for that user

$runs = Run::whereHas('times', function ($builder) use ($user) { 
        $query->where('user_id', $user->id);
    })->get();

Additionally if you want to eager load the times for that user and that user only you can add a constrainted with

$runs = Run::whereHas('times', function ($builder) use ($user) { 
        $query->where('user_id', $user->id);
    })->with(['times' => function ($query) use ($user) {
        $query->where('user_id', $user->id);
    }])->get();

edit:

The relationship between Runs and Users is effectively a many to many relationship with Times acting as a pivot model. Laravel supports this type of arrangement so let's set that up.

use Illuminate\Database\Eloquent\Relations\Pivot;

class Time extends Pivot
{
     public function run()
     {
         return $this->belongsTo('\App\Run');
     }

    public function user()
    {
         return $this->belongsTo('\App\User');
    }
}
class User extends Model
{
    public function times()
    {
        return $this->hasMany('\App\Time');
    }

    public function runs()
    {
        return $this->belongsToMany('\App\Run')->using('\App\Time');
    }
}
class Run extends Model
{
    public function times()
    {
        return $this->hasMany('\App\Time');
    }

    public function users()
    {
        return $this->belongsToMany('\App\User')->using('\App\Time');
    }
}

So now you can query all the runs for a specific user, and because it's using Time as a pivot table you know that the user will have a time for all the runs it returns

User::find(1)->runs();

All users who participated in a run

Run::find(1)->users();
11
  • Thanks for this Alec - I have re-factored the relationship to hasManyThrough but am getting an error of a missing column name "runs.time_id" when dumping... "{{dd($user->runs)}}". Am I going about this relationship the wrong way? I don't want to bodge it together, I'd rather do this correctly from the outset than making things more complicated than they need to be Dec 18, 2019 at 20:35
  • Honestly I think defining Time::class as a custom pivot model is the best way to go, it is effectively a pivot table between User::class and Run::class as is. I'll edit my answer with some steps on how to do that. Time::class doesn't have an 'id' correct?
    – Alec Joy
    Dec 18, 2019 at 20:49
  • Okay my answer is updated with a setup for turning Time::class into a custom pivot model which will let you directly access a users runs with $user->runs. You should absolutely still be able to access the direct relationships, like get all times for a user $user->times or all times for a run $run->times
    – Alec Joy
    Dec 18, 2019 at 21:03
  • Thanks Alec! I shall try this first thing tomorrow. (Times does have an ID - yes, I used it for deleting and editing users times - but I'm guessing I can do this via eloquant and detaching? Dec 18, 2019 at 21:06
  • You can yes, if you want to keep the id just add the following to your Time::class below the $fillable property public $incrementing = true;
    – Alec Joy
    Dec 18, 2019 at 21:09
0

Re-read your requirement:

"where a user has a TIME ( ... )"

You need to use has('times') to load Run records where the relationship is present. with() does not constrain the query, it only eager loads the relationship:

$runs = Run::has('times')->with('times')->where('user_id', $user->id)->get();

Note: You can use both has() and with() in a single query to constrain the parent Model and eager load the relationship for easier use later.

Edit: There may be an issue with ->where('user_id', $user->id);, but if you already have $user, you can query against that directly:

$runs = $user->runs()->has('times')->with('times')->get();

Note: This assumes your relationships are formed correctly, but it's unclear how User, Run and Time are all connected. As stated in the comments, the database structure doesn't currently support the proposed logic.

4
  • This doesn't seem right, using has() alone just finds all runs that have times, and the ->where here should apply to Run() now to the times based on the docs. I think whereHas() may be the solution here
    – Alec Joy
    Dec 18, 2019 at 20:06
  • You're likely correct on that. whereHas() is an extension of has() with additional logic. I was assuming the where('user_id', $user->id) was functioning (and I would have expected an error Column not found if it wasn't.)
    – Tim Lewis
    Dec 18, 2019 at 20:09
  • Yeah, the database structure listed doesn't provide a method to form that relationship between runs and users so there is probably something missing here. I'm not really sure.
    – Alec Joy
    Dec 18, 2019 at 20:10
  • Yeah, I'm not really sure either. I think the core issue is not understanding how has() and with() function differently, but the missing database logic definitely obfuscates the issue further... Hopefully you'll get a reply.
    – Tim Lewis
    Dec 18, 2019 at 20:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.