php - Laravel multiple many to many relationships? -


so using laravel , running issue, have relational model adsale, have setup hasone relationship adimpressions. example grab adsale records userid = 1. 5 different rows back, each of 5 rows have 5 adimpression rows match , have info clicks , impressions. end goal adimpression rows. when run has 1 impressions() method undefined method. if foreach on adsale records individually , run impresssions() method works. here code

class adsale extends eloquent{       protected $table = 'adsale';      public function impressions()      {          return $this->hasone('adimpression','adsaleid','id');      }  } 

here connecting adsale respective adimpression via adsaleid in adimpression table.

this running in controller.

$sales= adsale::where('userid','=', 1)->get(); $impressions = $sales->impressions(); 

now expect $impressions variable have adimpressions entry correlates adsaleid, getting undefined function since there multiple values returned $salelocation. if change ->frist(); or foreach on $salelocation works not work. need able total values impressions whole. info awesome.

i 5 different rows back, each of 5 rows have 5 adimpression rows match , have info clicks , impressions.

based on assume you're using wrong relationship.

1. change adsale model relationship

return $this->hasmany('adimpression','adsaleid'); 

2. use eager loading:

$sales = adsale::with('impressions')->where('userid', 1)->get(); 

3. access member, not method (relationship has been loaded)

foreach($sales $sale) {     foreach($sale->impressions $impression) {         //      }  } 

4. sum of impressions

$sale->impressions->count() 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -