So I am using laravel and I am running into an issue, so I have relational model AdSale, then I have that setup with a hasOne relationship with AdImpressions. So for example say I grab all AdSale records where userId = 1. I get 5 different rows back, for each of those 5 rows I have 5 adImpression rows that match and have info about clicks and impressions. My end goal is to get the AdImpression rows. However when I run my has one Impressions() method I get undefined method. However If I do a foreach on my AdSale records individually and then run my Impresssions() method It works. So here is my code
class AdSale extends Eloquent{
protected $table = 'AdSale';
public function impressions()
{
return $this->hasOne('AdImpression','adSaleId','id');
}
}
Here I am connecting my AdSale to its respective AdImpression via the adSaleId in the AdImpression table.
This is what I am running in my controller.
$sales= AdSale::where('userId','=', 1)->get();
$impressions = $sales->impressions();
Now what I expect from this is that my $impressions variable would have the AdImpressions entry that correlates to the adSaleId, however I am getting undefined function since there are multiple values returned to $saleLocation. If I change it to ->frist(); or do a foreach on $saleLocation it works but that will not work. I need to be able to total values from the impressions as a whole. Any info would be awesome.
I get 5 different rows back, for each of those 5 rows I have 5 adImpression rows that match and have info about clicks and impressions.
Based on that I assume that you're using the 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 as member, not method (relationship has already been loaded)
foreach($sales as $sale) {
foreach($sale->impressions as $impression) {
//
}
}
4. Get sum of impressions
$sale->impressions->count()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.