【问题标题】:Laravel 5 joining multiple tablesLaravel 5 加入多个表
【发布时间】:2017-07-10 01:57:15
【问题描述】:

我在 Laravel 中加入表格时遇到了真正的问题。

我可以加入 2 个表,但一旦我尝试加入第三个表,我就没有数据

class Main extends Model
{
    protected $table = 'main';
    protected $primaryKey = 'id';

    public function test() 
    {
        return $this->hasOne('App\Models\Test', 'id', 'id');
    }

    public function row() 
    {
        return $this->hasOne('App\Models\Row', 'id', 'id');
    }
}

class Test extends Model
{
    protected $table = 'test';
    protected $primaryKey = 'id';

    public function main() 
    {
        return $this->belongsTo('App\Models\Main', 'id', 'id');
    }

    public function rows() 
    {
        return $this->hasMany('App\Models\Row', 'id', 'id');
    }
}

class Row extends Model
{
    protected $table = 'row';
    protected $primaryKey = 'id';

    public function main() 
    {
        return $this->belongsTo('App\Models\Main', 'id', 'id');
    }

    public function rows() 
    {
        return $this->belongsTo('App\Models\Test', 'id', 'id');
    }
}

我已将此添加到我的主模型中以运行查询。这将输出 2 个表

public function scopeGetPart($query, somefield)
{
    return $query->with('test.main')
        ->where('somefield', somefield);
} 

这在我通过 phpMyAdmin 运行时有效。我想用 Laravel 的方式写这个

SELECT * FROM
    main
        INNER JOIN test ON
            main.id = test.id
        INNER JOIN row ON
            main.id = row.id
                AND main.my_field = row.my_field
WHERE somefield = 103288

【问题讨论】:

    标签: sql join laravel-5


    【解决方案1】:

    没有运行你的代码,你试过$main->with('test.rows')吗?这应该使用测试的行来获取主实例的测试。

    【讨论】:

    • 我所有的其他查询和连接都可以正常工作,如何回显原始 SQL 以便我可以看到正在运行的内容?
    【解决方案2】:

    我放弃了 Eloquent,因为它会导致问题,而是使用它来代替我想要的效果

    DB::table('main')
        ->join('test', 'main.id', '=', 'test.id')
        ->join('row', function ($join) {
             $join->on('main.id', '=', 'row.id')
                  ->whereRaw('main.my_field= row.my_field');
             })
        ->where('somefield', '103288');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2016-01-20
      • 1970-01-01
      • 2015-11-12
      • 2017-07-04
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多