2017-07-23 147 views
0

有人可以請解釋hasManyThrough如何涉及我想要達到的sql語句嗎?Laravel 5.4 hasManyThrough

--offers table 
    id, network_id, mobile_id 

--networks table 
    id, name 

--mobiles table 
    id, name 

我試圖讓手機與::(「網絡」)

我會寫爲

SELECT DISTINCT networks.name from networks, offers where offers.network_id = networks.id and offers.mobile_id in (1,2,3,4) 

關於上述SQL語句哪裏各精氨酸直播hasManyThrough方法?即

hasManyThrough(Network::class,Offer::class,'network_id','mobile_id') 

回答

0

我覺得這是多對多的關係

--offers table 
    id, network_id, mobile_id 

--networks table 
    id, name 

--mobiles table 
    id, name 

網絡模型

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Network extends Model 
{ 
    public function mobile(){ 
     return $this->belongsToMany('App\Mobile', 'offers')->withPivot('mobile_id'); 
    }  
} 

手機型號

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Mobile extends Model 
{ 
    public function network(){ 
     return $this->belongsToMany('App\Network', 'offers')->withPivot('network_id'); 
    }  
} 

您可以使用透視來獲取關係 對於更多信息訪問Laravel Docs

但是,對於這種情況,您必須使用數據透視表,即mobile_network而不是商品。

+0

我試圖避免一個額外的數據透視表,因爲offer表是一個包含所有需要的id的數據透視表,但我認爲你是對的,謝謝。 – futureweb