MySQL与多个表的关系 [英] MySQL relation with multiple tables

查看:71
本文介绍了MySQL与多个表的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个mysql表,如下所示:

I have 4 mysql tables, as the following:

 Makes:
 id - make_name

 Models:
 id - model_name - make_id

 Trims:
 id - trim_name - model_id

 Forsale_Cars:
 id - trim_id - year - price

在Makes表中,我有约700条记录,所以我的问题是,如何获取要出售表中只有一个子装饰的Makes列表?

in the Makes table I have ~700 records, so my question is, how can get a list of Makes which only have a child trim in the forsale table?

我在Forsale表中有20条记录,我想获取这些汽车的Makes列表.

I have 20 records in the forsale table, I want to get the list of Makes for these cars.

我正在使用Laravel,因此,如果有人实现了以前使用雄辩的语言会很棒的

I am using Laravel, so if anybody has achieved that previously using eloquent it will be great

推荐答案

雄辩的方式:

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

具有正确关系的模型(如果在某个地方有实际关系,可以用hasOne替换hasMany):

Models with correct relations (hasMany can be replaced with hasOne if that's actual relation somewhere):

// 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');
}

这篇关于MySQL与多个表的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆