2017-02-20 103 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');