简体   繁体   中英

How can I map a relationship with two options as a foreign key in Laravel?

Here are two models I have, should be self exlanatory.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Clan extends Model
{
    protected $table = 'clans';
}

class ClanMatch extends Model
{
    protected $table = 'clan_matches';
}

I need to create a function inside Clan model to fetch the matches. The way my database is currently set up there are two fields, home_clan_id and away_clan_id, it could be either.

How can I set up the relationship to check both? Here is how I would do it via eloquent.

$matches = ClanMatches::where('home_clan_id', $this->id)
->orWhere('away_clan_id', $this->id)->get();

You might want to use a Query Scope :)

public function scopeMatches($query)
{
    return $query->where('home_clan_id', $this->id)->orWhere('away_clan_id',$this->id);
}

Then you can call Model::matches()->get() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM