当我尝试使用belongsToMany方法时,只有在连接之后,我才会出现Laravel的奇怪行为。 我有这些课程:会议,订单,组织者,用户和产品 和这些数据透视表:meeting_organizer,order_product,organizer_user 这是订单类
class Order extends \Eloquent {
public function meeting(){
return $this->belongsTo('Meeting');
}
public function state(){
return $this->belongsTo('OrderState', 'order_state_id');
}
public function products(){
return $this->belongsToMany('Product')->withPivot('qty');
}
public function sellers(){
$meeting = $this->meeting()->first();
if($meeting) return $meeting->sellers()->get();
else return array();
}
public function organizers(){
$meeting = $this->meeting()->first();
if($meeting) return $meeting->organizers()->get();
else return array();
}
当我使用
时$data['records'] = Order::all();
然后循环:
foreach( $data['records'] as $r ){
if($r->meeting){
$r->meeting_date = $r->meeting->date;
$r->meeting_name = $r->meeting->name;
}
$r->status = $r->state->name;
$r->delivery_date = date_format(date_create($r->delivery_date), 'm-d');
$r->seller = '';
foreach( $r->sellers() as $s) $r->seller .= $s->name.', ';
$r->organizer = '';
foreach( $r->organizers() as $o) $r->organizer .= $o->name.', ';
$r->product = '';
foreach( $r->products as $p) $r->product .= $p->pivot->qty ." x ". $p->name.'<br />';
}
效果很好。
但如果我使用此连接
$data['records'] = Order
::join('meeting_organizer', 'orders.meeting_id', '=', 'meeting_organizer.id')
->join('organizer_user', 'meeting_organizer.organizer_id', '=', 'organizer_user.organizer_id')
->where('organizer_user.user_id', '=', Auth::user()->id)->get();
循环不返回任何产品。 所以,我没有得到任何错误,只是一个空洞的结果。
如果我尝试在我的循环$r->id
内的屏幕上打印,结果是错误的并且所有记录的编号都相同,但所有其他属性都是正确的。