Mysql
 sql >> Datenbank >  >> RDS >> Mysql

MySQL-Relation mit mehreren Tabellen

Eloquent:

// Makes that have forsale nested relation
Make::whereHas('models', function ($q) {
    $q->whereHas('trims', function ($q) {
        $q->has('forsales');
    });
})->get(); // returns Eloquent Collection

Modelle mit korrekten Beziehungen (hasMany kann durch hasOne ersetzt werden, wenn das irgendwo die tatsächliche Beziehung ist):

// Make model
public function models()
{
    return $this->hasMany('CarModel');
}

// CarModel (as you can't use Model name)
public function trims()
{
    return $this->hasMany('Trim');
}
public function make()
{
    return $this->belongsTo('Make');
}

// Trim model
public function forsales()
{
    return $this->hasMany('Forsale');
}
public function carModel()
{
    return $this->belongsTo('CarModel');
}

// Forsale model
public function trim()
{
    return $this->belongsTo('Trim');
}