Monday, March 6, 2017

(Laravel) Join 3 or more tables using "Eloquent Relationships"

I'm trying to join 3 tables using eloquent relationships, but it doesn't give the expected results.

Shipment model

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

to get the data i'm using this code

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

I'm trying to make it equivalent to this query

 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

The first query returns all the data in 3 tables, but when the second one returns Release only and this what I want

I only want the data that has relation among these three tables not everything

What I'm doing wrong ?



via Ahmadz Issa

Advertisement