【问题标题】:How to retrieve data through model?如何通过模型检索数据?
【发布时间】:2018-11-19 08:47:45
【问题描述】:

我有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

【问题讨论】:

  • OrderPhoto-Photo 真的是多对多的关系吗?对我来说没有多大意义。
  • 可以使用with获取查询中的相关表。看看this。 Order::with('related_table_name')->get();
  • 我需要通过另一个模型连接模型
  • 似乎订单照片应该是照片和订单之间的中间表。否则没有多大意义。
  • @OPV 提供四个 (?) 表中的数据样本和您想要的输出。

标签: laravel laravel-5


【解决方案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

【讨论】:

  • 你能帮忙解决hasManyThrough中的密钥吗?
  • 在我的情况下OrderPhoto 是中间表
  • 我在问题中添加了查询
  • 为我工作:return $this->hasManyThrough('App\Photo', 'App\OrderPhoto', 'Photos_Id' , 'Id', 'Id', 'Orders_Id'); 我正确吗?
  • 尝试运行它,如果你得到你正在运行的结果,否则它通常会通过错误或发回一个空集合
猜你喜欢
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 2013-08-13
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多