【问题标题】:how to load nested relationships in laravel如何在laravel中加载嵌套关系
【发布时间】:2019-04-29 12:44:22
【问题描述】:

我有 3 个模型,我想从 a 开始并加载与 b 的关系,我也想在 a 中加载 b 和 c 之间的关系,这可能吗?这是我想在代码中做的事情:

AccommodationRoomModel which is the B model:
public function accommodation(){
        return $this->belongsTo(Accommodation::class);
    }

  public function roomPricingHistory(){
    return $this->hasMany(RoomPricingHistory::class);
}

在住宿模式中:

public function accommodationRoom()
{
    return $this->Hasmany(AccommodationRoom::class);
}

最后是房间定价历史:

 public function accommodationRoom(){
    return $this->belongsTo(AccommodationRoom::class);
}

现在在我的住宿控制器中,我想获得房间内的所有住宿,我想从房间获得价格,所以这里是它

A = Accomodation
B = Room
C = price

我想这样打电话

From A get B and The relation Of it with C and show all in A

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以为此使用 Laravel 嵌套预加载:

    来自docs

    要急切加载嵌套关系,您可以使用“点”语法。为了 例如,让我们急切地加载这本书的所有作者和所有 一篇 Eloquent 声明中的作者个人联系方式:

    $books = App\Book::with('author.contacts')->get();
    

    在你的情况下:

    $accomodations = Accomodation::with('accommodationRoom.roomPricingHistory')->get();
    

    【讨论】:

      【解决方案2】:

      nested-eager-loading

      A::with('B.C');

      【讨论】:

        猜你喜欢
        • 2018-06-03
        • 2019-07-25
        • 2017-09-30
        • 2016-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-16
        • 2020-05-10
        相关资源
        最近更新 更多