AOWulin Guide
AOWulin Guide

Reputation: 13

DB query to relationship

My query:

$data = DB::table('countries')
        ->leftJoin('matches', function ($join) {
            $join->on('matches.hometeam', '=', 'countries.id')
            ->orOn('matches.awayteam', '=' ,'countries.id');
        })
        ->where('countries.id', $id)->get();

        return dd($data);

How can I get same results using relationship?

Upvotes: 0

Views: 165

Answers (1)

Insax
Insax

Reputation: 622

In your Model (You need a matches model aswell):

<?php
class Country extends Model {
  public function matches() {
    return $this->hasMany(App\Matches::class, ['hometeam', 'awayteam'], 'id');
  }
}

In your controller:

$countrys = Countrys::where('id', $id)->get()
foreach($countrys as $country) {
  var_dump($country->matches);
}
die();

Upvotes: 1

Related Questions