2017-02-20 105 views
0

我在加入Laravel中的表格时遇到了实际问题。Laravel 5加入多个表格

我可以加入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 

回答

0

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

+0

我的所有其他查询,并加入完美地工作,怎么样呼应的原始SQL,所以我可以看到发生了什么跑? – AdRock

0

我放弃了与雄辩,因为它是造成问题,并用这个代替其工作我如何想

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