雄辩的联接返回空数据集

时间:2019-02-12 07:28:07

标签: laravel eloquent

我正在尝试加入3个表,分别是-客户,customer_item和项目。

  • 客户-客户详细信息
  • 项目-项目详细信息
  • customer_item-客户与项目之间的关系

客户-型号

public function itemRel(){
    return $this->hasMany(CustomerItem::class,'customer_id');
}

CustomerItem-模型

public function itemDetails(){  
    return $this->hasOne(Items::class, 'id');
}

CustomerController

$customer = Customers::find($id);
$data = $customer->itemRel();
return $data;

架构结构

customer - [id,name,mobile,username...]
items - [id, item_name, quantity, nature ....]
customer_item - [id, customer_id,item_id...]

我想列出与用户(customer_item)相关的所有项目

4 个答案:

答案 0 :(得分:1)

尝试改用belongsToMany关系

客户-型号

public function items(){
    return $this->belongsToMany(Items::class,'customer_item','customer_id','item_id');
}

项目-型号

public function customers(){    
    return $this->belongsToMany(Customer::class,'customer_item','item_id','customer_id');
}

CustomerController

$customer = Customers::find($id);
$data = $customer->items();
return $data;

答案 1 :(得分:0)

请更改您的模型代码,例如:

客户-型号

public function itemRel(){
    return $this->belongsTo(CustomerItem::class,'customer_id');
}

CustomerItem -模型

public function customer(){  
    return $this->hasMany(Customer::class);
}

更新后的答案

客户-型号

public function itemRel(){
    return $this->hasMany(CustomerItem::class);
}

CustomerItem -模型

public function customer(){  
    return $this->belongsTo(Customer::class, 'customer_id');
}

答案 2 :(得分:0)

尝试一下:

$customer = Customers::with('itemRel')->find($id);
$data = $customer->itemRel;
return $data;

我希望这会有所帮助。

答案 3 :(得分:0)

不带括号使用它

$data = $customer->itemRel;

获取实际使用的模型数据

$data->propertyName