locnguyen
locnguyen

Reputation: 841

Laravel Multiple Models Eloquent Relationships Setup?

I have 3 models

User Pick Schedule

I'm trying to do something like the following

$picksWhereGameStarted = User::find($user->id)
                                ->picks()
                                    ->where('week', $currentWeek)
                                    ->first()
                                ->schedule()
                                    ->where('gameTime', '<', Carbon::now())
                                    ->get();

This code only returns one array inside a collection. I want it to return more than 1 array if there is more than 1 result.

Can I substitute ->first() with something else that will allow me to to return more than 1 results.

If not how can I set up my models relationship to allow this to work.

My models are currently set up as follow.

User model

public function picks()
{
    return $this->hasMany('App\Pick');
}

Schedule model

public function picks()
{
    return $this->hasMany('App\Pick');
}

Pick model

public function user()
{
    return $this->belongsTo('App\User');
}

public function schedule()
{
    return $this->belongsTo('App\Schedule');
}

Upvotes: 1

Views: 1154

Answers (2)

Sandyandi N. dela Cruz
Sandyandi N. dela Cruz

Reputation: 1345

Since you already have a User model (you used it inside you find method as $user->id), you can just load its Pick relationship and load those Picks' Schedule as follows:

EDIT: Assuming you have a schedules table and your picks table has a schedule_id column. Try this.

$user->load(['picks' => function ($q) use ($currentWeek) {
    $q->join('schedules', 'picks.schedule_id', '=', 'schedules.id')
        ->where('schedules.gameTime', '<', Carbon::now()) // or Carbon::now()->format('Y-m-d'). See what works.
        ->where('picks.week', $currentWeek);
}])->load('picks.schedule');

EDIT: The code above should return the user's picks which have a schedules.gameTime < Carbon::now()

Try it and do a dump of the $user object to see the loaded relationships. That's the Eloquent way you want.

Tip: you may want to do $user->toArray() before you dump $user to see the data better.

EDIT: The loaded picks will be in a form of Collections so you'll have to access it using a loop. Try the following:

foreach ($user->picks as $pick) {
    echo $pick->schedule->gameTime;
}

If you only want the first pick from the user you can do: $user->picks->first()->schedule->gameTime

Upvotes: 1

Jon Tan
Jon Tan

Reputation: 1551

I think a foreach loop may be what you're looking for:

$picks = User::find($user->id)->picks()->where('week', $currentWeek);
foreach ($picks as $pick){
    $pickWhereGameStarted = $pick->schedule()->where('gameTime', '<', Carbon::now())->get();
}

Try this and see if it's working for you

Upvotes: 0

Related Questions