如何在Laravel-Eloquent模型中连接三个表。我的桌子结构是这样的。使用raw(带有左联接的mysql(查询可以很容易地获得所需的结果,但也可以通过Eloquent获得。
客户表
id
title
name
订单表(具有客户id(
id
customer_id
工时表(具有订单id(
id
order_id
从小时模型中,我想获得客户详细信息和订单详细信息现在我可以获得如下订单详细信息。
public function order()
{
return $this->belongsTo('App'Models'Order', 'order_id', 'id');
}
如何获取客户详细信息?
我尝试了如下,但没有获得成功
1.return $this->hasManyThrough('App'Models'Customer','App'Models'Order','customer_id','id');
2. return $this->hasManyThrough('App'Models'Customer','App'Models'Order','customer_id','order_id');
编辑1:
class HourLogging extends Model
{
public function order()
{
return $this->belongsTo('App'Models'Order', 'order_id', 'id');
}
$timeoverview = HourLogging::select('hour_logging.*')->whereRaw("hour_logging.date BETWEEN '".$start_date."' AND '".$end_date."'")->orderBy('date','asc');
$timeoverview->with('order.customer');
return $timeoverview->get();
}
class Order extends Model {
public function customer() {
return $this->belongsTo('App'Models'Customer');
}
}
hasManyThrough的工作方式与您试图实现的目标相反。它可以让您轻松地从客户模型中获得小时型号。
为了获得所需内容,您需要定义从小时到订单再到客户的其他关系。将以下关系添加到您的模型中:
class Hour extends Model {
public function order() {
return $this->belongsTo('App'Models'Order');
}
}
class Order extends Model {
public function customer() {
return $this->belongsTo('App'Models'Customer');
}
}
有了这些关系,您应该能够使用$hour->Order访问订单数据,使用$hour->Order->Customer来访问Customer 需要记住的一点是:Eloquent提供了急切地加载相关数据以避免额外查询的可能性。当您同时获取多个Hour记录时,这样做是有意义的。您可以用以下内容加载所有小时记录以及相关的订单和客户数据:$hours = Hour::with('order.customer')->get();