(Laravel)使用“Eloquent Relationships”加入3个或更多表

时间:2017-03-06 12:26:51

标签: mysql sql-server database laravel join

我正在尝试使用雄辩的关系加入3个表,但它没有给出预期的结果。

货件型号

class Shipment extends Model
{
    protected $table = 'ccctadm.Shipment';

    public function customergroupcode()
    {
        return $this->hasMany(DocumentRuleSet::class,'customergroupcode','customergroupcode');
    }
    public function shipmentcategory()
    {
        return $this->hasMany(DocumentRuleSet::class,'shipmentcategory','shipmentcategory');
    }

    public function status()
    {
        return $this->hasMany(DocumentRuleSet::class,'status','status');
    } 
} 

获取我正在使用此代码的数据

   $shipment_data = Shipment::With(['customergroupcode' , 'shipmentcategory','status'])->
Where('shipment_cycle','!=','closed')->get();

我试图让它等同于这个查询

 select B.rulesetname,B.icon ,COUNT(*)As Total  from
[ccct].[ccctadm]. [Shipment] A  INNER  JOIN 
[ccct].[ccctadm].[documentruleset] B
     ON
      A.customergroupcode = B.customergroupcode  AND A.shipmentcategory =  
   B.shipmentcategory AND A.status = B.status INNER
JOIN [ccctadm].[shipassign] S ON  A.id = S.shipmentid AND
 A.shipment_cycle != 'closed'  GROUP BY  rulesetname,B.icon

第一个查询返回3个表中的所有数据,但是当第二个查询返回Release时,这就是我想要的

我只想要这三个表之间关系的数据不是一切

我做错了什么?

1 个答案:

答案 0 :(得分:0)

使用has()方法。它根据关系的存在限制记录。

$shipment_data = Shipment::has('customergroupcode' , 'shipmentcategory','status')->
Where('shipment_cycle','!=','closed')->get();