如何通过模型检索数据?

问题描述 投票:1回答:1

我有Order模型与另一种关系OrderPhoto

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

反过来OrderPhoto模型有关系:

public function Photo()
{
  return $this->belongsToMany('App\Photo');
}

那么,如何从OrderModel获取来自第三个模型Photo的相关数据?

我想这个:

Order::with("OrderPhoto.Photo")->get();

Photo模型中仅检索每个Order的数据

因此,每个Order有一些OrderPhotos。关系是一对多的。

OrderPhotos的一个项目与表Photos的主键有关。这是一对一的关系。

我的结果查询应该是:

select `photos`.*, `ordersphoto`.`Orders_Id` from `photos` inner join `ordersphoto` on `ordersphoto`.`Photos_Id` = `photos`.`Id` where `ordersphoto`.`Orders_Id` in (1);

如何使用hasManyThrough进行此查询?

laravel laravel-5
1个回答
1
投票

只需快速查看您的关系,您就可以在订单模型上创建一个hasManyThrough关系。

public function Photo {
    return $this->hasManyThrough('App\OrderPhoto', 'App\Photo')
}

您可能需要添加表键才能使其正常工作

这将允许您:

Order::with("Photo")->get();

你可以在这里看到更多细节https://laravel.com/docs/5.5/eloquent-relationships#has-many-through

更新

试试这个

public function Photo {
    return $this->hasManyThrough('App\Photo', 'App\OrderPhoto', 'Order_id', 'Photos_id', 'id', 'id')
}

使用此信息让您的数据库结构变得有点困难,但您应该能够解决这个问题。这也可能有所帮助

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_hasManyThrough

© www.soinside.com 2019 - 2024. All rights reserved.