mercredi 18 décembre 2019

Laravel - Getting parent data depending on child association

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:

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);
    }

}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire