kittycat
kittycat

Reputation: 15

What do I find related models using eloquent in Laravel?

I have two table rounds and assignments. Its corresponding models are Assignment and Round. Assignment Have relation to round is

public function round()
    {
        return $this->belongsTo(Round::class, 'round_id');
    }

assignment have reference key as round_id. I want to get all assignments have the round_id.

$assignments = Assignment::find(1)->round()->where('start_date', '<=', $now)
 ->where('end_date', '>=', $now)
 ->where('round_type', '=', 'judge')
 ->get();

Upvotes: 0

Views: 39

Answers (2)

Kalesh Kaladharan
Kalesh Kaladharan

Reputation: 1058

You should try whereHas

$assignments = Assignment::whereHas('round', function($query) use ($round_id, $start_date, $end_date, $round_type){
    $now = Carbon::now();

    $query->where('id', $round_id);
    $query->where('start_date', '<=', $now);
    $query->where('end_date', '>=', $now);
    $query->where('round_type', $round_type);
})->get();

This will get you all the assignments of round round_id and in the date range $start_date and $end_date

Upvotes: 1

brice
brice

Reputation: 1881

You can add a where clause to filter assignments by round_id.

$round_id = 1;

$assignments = Assignment::where('round_id', $round_id)->get();

You can chain multiple where clauses.

$assignments = Assignment
                   ::where('round_id', $round_id)
                   ->where('round_type', '=', 'judge')
                   ->get();

Upvotes: 0

Related Questions