samedi 11 août 2018

Join one to many models with sum using eloquent on laravel

below work fine but I want to change it to two models(one to many relationship) how can I write the query?

Big::query()
->      select('A.id','A.product')
        ->addSelect(DB::raw('SUM(CASE WHEN B.approve = 1 THEN 1 
                                      WHEN B.approve = -1 THEN -1 ELSE 0 END) as approveshow'))                              
        ->from('Bigs as A')
        ->leftjoin('Smaills as B', function($join) {
            $join->on('A.ID', '=', 'B.p_id');
            })
        ->groupBy('A.id','A.product')
        ->whereIn('A.id',$wantids)
        ->get();

I write the model like this ~~~Model Big~~~

class Big extends Model
{
       public function smalls()
    {
        return $this->hasMany('App\Models\Big','p_id','id');
    }
}

~~~Model Small~~~

class Small extends Model
{
    public function big()
    {                   
        return $this->belongsTo('App\Models\Big','p_id','id');
    }
}

how can I join two models using eloquent and use sum raw function?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire