Laravel雄辩关系模型

时间:2015-11-24 06:48:53

标签: laravel eloquent relationship

我的数据库上有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

但它对我不起作用..

有什么想法可以称之为祖父母关系吗?

2 个答案:

答案 0 :(得分:0)

为订单模型添加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中的更多信息。

答案 1 :(得分:0)

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

// 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文件夹的子项。