【问题标题】:Laravel 5.0 Eloquent 3rd level relationshipsLaravel 5.0 Eloquent 3 级关系
【发布时间】:2018-10-08 04:34:49
【问题描述】:

我有三张桌子

属性:

  1. property_id
  2. 标题

房产价格:

  1. property_price_id
  2. currency_id
  3. 价格

货币

  1. currency_id
  2. 标题

属性模型:

public function PropertyPrice(){
    return $this->hasMany('App\PropertyPrice','property_id');
}

物业价格模型:

 public function Currency(){

         return $this->belongsTo('App\Currency','currency_id');  
}

 public function Property(){

       return $this->belongsTo('App\Property','property_id');
}

货币模型

public function PropertyPrice(){

  return $this->hasMany('App\PropertyPrice','currency_id');
}

现在我正在运行这个 Eloquent 命令来获取带有价格的属性,

Property::with('PropertyPrice')->orderBy('ordering','desc')->paginate(10);

但我很困惑如何获得货币名称?请注意,我在“有很多通过”下看到了官方文档中提供的示例,但它是一个不同的示例,我无法与之相关。

请帮忙,谢谢

【问题讨论】:

    标签: laravel-5 eloquent relationship


    【解决方案1】:
    $properties = Property::with('PropertyPrice')->orderBy('ordering','desc')->paginate(10);
    

    然后

    foreach ($properties as $property) {
        $currency_title = $property->PropertyPrice->Currency->title;
    }
    

    使用相同的逻辑,您也可以在视图中执行此操作

    【讨论】:

    • 谢谢兄弟,我通过实验得到了答案,但您的提示也非常有益,感谢您的宝贵时间
    【解决方案2】:

    我做了一些实验,找到了答案,

    Property::with(['PropertyPrice' => function($query){
                                          $query->with('Currency');
                                       }
                   ])->orderBy('ordering','desc')->paginate($per_page);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-02
      • 2021-05-06
      • 2014-12-27
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      相关资源
      最近更新 更多