dongxiee0744 2016-02-25 05:04
浏览 55
已采纳

Laravel 5.2有很多关系问题

I have 3 tables: orders, codes, events

I want to be able to pull all events that an order has, but there's an intermediary table that acts as a pivot table. I've been trying to use hasManyThrough and belongsToMany (along with withPivot) without any luck.

Examples:

public function events()
{
    return $this->belongsToMany('events'); // tried this, fails
    return $this->hasManyThrough('events', 'codes'); // tried this, fails
    return $this->hasManyThrough('events', 'codes', 'event_id', 'id'); // tried this, fails
}

Any pointers would be great!

example image

  • 写回答

2条回答 默认 最新

  • dsy48837 2016-02-25 05:09
    关注

    That's a belongsToMany setup. First, the first parameter is the name of the related class. Second, since your pivot table doesn't follow the Laravel naming conventions, you need to specify the name of the pivot table in your relationship definition:

    public function events()
    {
        // first parameter is the name of the related class
        // second parameter is pivot table name
        return $this->belongsToMany(Event::class, 'codes');
    }
    

    With this setup, you can do:

    // get an order
    $order = Order::first();
    
    // has all the events related to an order
    $events = $order->events;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源