简体   繁体   English

Laravel有多对多关系?

[英]Laravel multiple many to many relationships?

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. 因此,我使用的是laravel,遇到了一个问题,因此,我使用了关系模型AdSale,然后使用具有与AdImpressions的hasOne关系的设置。 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. 例如,假设我抓取了userId = 1的所有AdSale记录。我得到了5个不同的行,对于这5行中的每行,我都有5个adImpression行,这些行匹配并具有有关点击和展示的信息。 My end goal is to get the AdImpression rows. 我的最终目标是获取AdImpression行。 However when I run my has one Impressions() method I get undefined method. 但是,当我运行我的一个Impressions()方法时,会得到未定义的方法。 However If I do a foreach on my AdSale records individually and then run my Impresssions() method It works. 但是,如果我分别对我的AdSale记录执行一次foreach,然后运行我的Impresssions()方法,则该方法有效。 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. 在这里,我通过AdImpression表中的adSaleId将我的AdSale连接到其相应的AdImpression。

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. 现在,我由此期望的是,我的$ impressions变量将具有与adSaleId相关的AdImpressions条目,但是由于越来越多的值返回到$ saleLocation,所以我得到了未定义的函数。 If I change it to ->frist(); 如果我将其更改为-> frist(); or do a foreach on $saleLocation it works but that will not work. 或在$ saleLocation上执行foreach,但该方法不起作用。 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. 我得到5个不同的行,对于这5行中的每行,我都有5个adImpression行,这些行匹配并具有有关点击和展示的信息。

Based on that I assume that you're using the wrong relationship. 基于此,我认为您使用的是错误的关系。

1. Change AdSale model relationship 1.更改AdSale模型关系

return $this->hasMany('AdImpression','adSaleId');

2. Use eager loading : 2.使用紧急加载

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

3. Access as member, not method (relationship has already been loaded) 3.以成员身份访问,而不是方法访问​​(关系已经加载)

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

4. Get sum of impressions 4.获取印象总数

$sale->impressions->count()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM