S
S
Sergey2020-02-10 11:01:42
Laravel
Sergey, 2020-02-10 11:01:42

How in Laravel to build relationships of one child model with another through the parent?

Good afternoon!

I have three tables:

projects
    id - integer
    name - string

clients
    id - integer
    project_id - integer
    name - string

metricas
    id - integer
    project_id - integer
    title - string


Accordingly, in the parent Project model, I prescribe the following relationships with Client and Metrica:

class Project extends Model
{
    public function client()
    {
        return $this->hasOne(Client::class);
    }

    public function metrica()
    {
        return $this->hasOne(Metrica::class);
    }
}


Well, in Client and Metrica, I prescribe the standard belongsTo () relations

class Client extends Model
{
    public function project()
    {
        return $this->belongsTo(Project::class);
    }
}

class Metrica extends Model
{
    public function project()
    {
        return $this->belongsTo(Project::class);
    }
}


Question: how to register the relationship between Client and Metrica?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2020-02-10
@SVZhidkow

Very easy.

Client:

hasMany(Metric::class, 'project_id', 'project_id')

Metric:

hasMany(Client::class, 'project_id', 'project_id')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question