【问题标题】:Laravel Eloquent Relation ModelLaravel Eloquent 关系模型
【发布时间】:2016-02-26 12:13:37
【问题描述】:

我的数据库中有 3 个表:

table 1 = user (hasMany order)
table 2 = order (hasMany order_detail, belongsTo user)
table 3 = order_detail (belongsTo order)

在我的 order_detail 模型上,我添加了这个功能:

public function order() {
    return $this->belongsTo('App\Order');
}

所以我可以在不从控制器定义的情况下调用订单数据,我只是在我的控制器上定义 order_detail

$order_detail->order->invoice_number

但是如何从订单明细中调用用户数据呢?

我试试这个

$order_detail->order->user

但它对我不起作用..

有没有办法调用祖父关系?

【问题讨论】:

  • @luigonsec 我已经成功创建了 2 个表关系,但现在要创建 3 个表?? $order_dettail->order->user->first_name
  • 您发布的内容应该有效。您能否发布有关如何设置关系的代码(而不是伪代码)?

标签: laravel eloquent relationship


【解决方案1】:

我认为这是定义关系的更完整的方式:

// User model

public function orders(){

    // I'm telling that users has many order. The orders have an user_id field that match with the ID field of the user.
    return $this->hasMany('App/Order', 'user_id' , 'id');

}


// Order model

public function order_details(){

    // I'm telling that order has many order_details. The order_details have an order_id field that match with the ID field of the order.
    return $this->hasMany('App/OrderDetail', 'order_id' , 'id');

}

public function user(){

    // I'm telling that an order belongs to an user. The user has an ID field that match with the order_id field of the order.
    return $this->belongTo('App/User', 'id', 'user_id');
}


// OrderDetail Model

public function order(){

    // I'm telling that an order detail belongs to an order. The order  has an ID field that match with the order_id field of the order detail.
    return $this->belongTo('App/Order', 'id', 'order_id');
}

我看到您只将模型名称作为关系定义中的第一个参数。我认为你必须把从根到模型的相对路径。就我而言,我将模型作为 App 文件夹的子项。

【讨论】:

    【解决方案2】:

    在订单模型中添加order_detail函数:

    public function order_details() {
        return $this->hasMany('order_detail');
    }
    

    对于用户:

    public function user() {
        return $this->belongsTo('user');
    }
    

    在用户模型中添加:

    public function orders() {
        return $this->hasMany('order');
    }
    

    然后,你可以在控制器中调用:

    $details = Order::find(1)->order_details->where('order_detail_id', 5)->first();
    $userName = $details->username;
                //           ^
                // column name in order_detail table
    

    更多信息请关注docs

    【讨论】:

    • 如何从order_detail中获取id为5的用户名?
    • 我更新了我的答案,但我不知道“id”是什么意思。是订单号吗?您可以在 where clausule 中更改列名。
    猜你喜欢
    • 2021-10-01
    • 2018-10-20
    • 2021-07-04
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多