2017-07-23 148 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