【问题标题】:How to retrieve multiple owners of a polymorphic relation in laravel 4如何在 laravel 4 中检索多态关系的多个所有者
【发布时间】:2013-05-26 07:00:49
【问题描述】:

下面列出了 3 个表格:
用户

id username

订单

id price  

历史

id historable_id historable_type 

我想在订单视图中检索所有具有特定历史 ID 的订单

订单型号:

public function history(){  
    return $this->morphMany('History','historable');} 

订单控制器:

public function index(){  
    var_dump(History::find(1)->historable->toArray());}  

历史 ID 为 1 的订单不止一个,但只找到第一个订单。如何获取具有相同历史 ID 的所有其他人?

【问题讨论】:

  • 也许我理解错了,但是你不想做 History::where('historable_id', '=', '1')->get() 吗?当前,您正在检索历史表中 ID 为 1 的行,而不是与 ID 为 1 的订单匹配的所有行。 find() 正在查看历史表上的“id”列,您想要查看在“historable_id”列中。
  • 谢谢,你是对的。

标签: laravel polymorphic-associations laravel-4 eloquent


【解决方案1】:

总结 cmets 中的讨论,解决方案是根据“historable_id”列而不是常规列检索记录。

History::where('historable_id', '=', '1')->get();

或者:

Order::find(1)->history;

【讨论】:

    猜你喜欢
    • 2019-11-14
    • 2020-11-14
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2013-09-14
    • 2014-08-13
    • 1970-01-01
    相关资源
    最近更新 更多