【问题标题】:joining tables in laravel elequent在 laravel eloquent 中加入表格
【发布时间】:2019-08-29 04:31:58
【问题描述】:

我如何在 laravel elequent 中加入这两个表并将它们作为一个表?

表1(基本信息):

id  baseId   Site_ID  region    city        address
1     123      321     west    wakanda      street2

表 2(基数):

base_id     First     Second   third  
1            54          52     51

我有这两个模型,无论它们是否正确:

class base extends Model
{
    public function Counts() {
    return $this->hasOne(CountInBase::class, 'base_id');
}

}

class CountInBase extends Model
{
    public function bases() {
        return $this->belongsTo(base::class ,'base_id','id');
    }
}

在控制器中我正在尝试进行此查询,但我没有得到预期的结果,我只是得到第一个表的结果:

$data = base::where('region' ,'=' ,'west')->with(['Counts'])->get();

【问题讨论】:

    标签: php laravel-5


    【解决方案1】:

    您可以像这样访问Counts 数据:

    foreach($data as $base) {
        // $base->Counts->First;
    }
    

    【讨论】:

    • 您能否就答案提供反馈?
    【解决方案2】:

    当您想将两个或多个不同的表连接为一个表时,您必须使用 join

     $integratedTable = \DB::table('bases')
            ->join('basecounts', 'bases.id', '=', 'basecounts.base_id')
            ->get();
    
     return $integratedTable;
    
    /*
    [
        {
        "id": 1,
        "baseId": 1,
        "Site_ID": 1,
        "region": "west",
        "city": "wakanda",
        "address": "street2",
        "base_id": 1,
        "First": 54,
        "Second": 52,
        "third": 51,
    
        }
    ]
    

    在mysql中有不同的方法可以连接两个或多个表:

    内联

    左连接

    右连接

    联合

    交叉连接或笛卡尔积

    自加入

    全外连接

    Laravel 支持他们。你可以看到它的文档here

    【讨论】:

    • 你没有答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2021-10-01
    • 2014-04-17
    • 2016-04-03
    • 1970-01-01
    • 2018-12-07
    • 2018-08-16
    相关资源
    最近更新 更多