Tor2r's avatar
Level 4

Relationship through.. kind of

Models

Competition

id
title

Season

id
competition_id
year

Tip (guessing the final standings of teams in a season)

id
season_id
slug
user_id
etc..

Is there a way to define the relationship between Tip and Competition? I want (or wish) I could do something like:

$team = Team::find(1);
$team->competition->title;

Allready know I cant get it as an attribute

public function getCompetitionAttribute()
{
    return $this->season->competition;
}

Maybe this is the only way?

0 likes
4 replies
gych's avatar

You can set up eloquent relations to achieve this result, below you can find some examples on how you could setup these relations. Before using my examples make sure that these are the relations you need for your use case.

Example relations for Tip model

    public function season()
    {
        return $this->belongsTo(Season::class);
    }

    public function competition()
    {
        return $this->hasOneThrough(Competition::class, Season::class);
    }

Example relations for Season model

    public function competition()
    {
        return $this->belongsTo(Competition::class);
    }

    public function tips()
    {
        return $this->hasMany(Tip::class);
    }

Example relations for Competition Model

    public function seasons()
    {
        return $this->hasMany(Season::class);
    }

    public function tips()
    {
        return $this->hasManyThrough(Tip::class, Season::class);
    }

More info about this in the docs: https://laravel.com/docs/10.x/eloquent-relationships https://laravel.com/docs/10.x/eloquent-relationships#has-one-through

kokoshneta's avatar

Are you sure your structure actually makes sense? I have no access to the contents or logic of your app, but just based on the model names, and assuming the app is sports-related, it doesn’t seem like your models relate to how things work in the real world.

Why does a season belong to a competition, and a team to a season? Can the same team not play in several seasons? And do specific competitions not usually belong to specific seasons, rather than the other way around?

Tor2r's avatar
Level 4

@kokoshneta

You are absolutely correct! I messed up in my original post. I've edited it now. (The team model is not relevant in my problem)

I'm making an app where you can guess the table standings. So Team should be "Tip". You make a Tip of how the league will end. So I want to get which competition a tip belongs to/ or is connected to.

gych's avatar

@Tor2r I've edited my first reply to match the changes you've made to your original post

Please or to participate in this conversation.