我该如何解决“关系'a不是HasOne或BelongsTo的实例”。在laravel里?

时间:2018-08-01 19:45:55

标签: laravel join eloquent laravel-5.6

我的laravel雄辩是这样的:

$query = ItemDetail::selectRaw('a.item_number, sum(abs(a.quantity)) as "total_quantity"')
              ->from('item_detail as a')
              ->join('items as b', 'b.id', '=', 'a.item_number');

if(isset($param['vendor'])) {
    $query = $query->where('b.vendor_id', '=', $param['vendor']);
}

$query = $query->groupBy('a.item_number')
               ->paginate($paged);

return $query;

如果执行查询,则存在这样的错误:

Relation 'a' is not instance of HasOne or BelongsTo.

我该如何解决这个问题?

更新

我的商品模型如下:

class Item extends Model
{
    ...
    protected $fillable = [
        'name',
        'vendor_id'
    ];
    public function item_details() 
    {
        return $this->hasMany(ItemDetail::class, 'id', 'item_number');
    }
}

我的商品详细信息模型如下:

class ItemDetail extends Model
{
    ....
    protected $fillable = [
        'item_number',
        'name',
        'posting_date'
    ];
    public function item()
    {
        return $this->belongsTo(Item::class, 'id', 'item_number');
    }
}

3 个答案:

答案 0 :(得分:1)

根据您的一些详细信息,请确认这是否是您想要的:

项目模型:

class Item extends Model
{
  ...
  protected $fillable = [
    'name',
    'vendor_id'
  ];

  public function item_details() 
  {
      return $this->hasMany(ItemDetail::class, 'item_number', 'id');
  }
}

ItemDetail模型:

class ItemDetail extends Model
{
  ....
  protected $fillable = [
    'item_number',
    'name',
    'posting_date'
  ];

  public function item()
  {
    return $this->belongsTo(Item::class, 'item_number', 'id');
  }
}

控制器方法:

$itemDetails = ItemDetail::whereHas('item', function($q) use ($param) {
    if (isset($param['vendor']){
        $q->where('vendor_id', '=', $param['vendor']);
    }
})
->selectRaw('item.id', 'item_detail.item_number', 'sum(abs(a.quantity)) as total_quantity')
->groupBy('item_number')->paginate($paged);

查看文件:

@foreach($itemDetails as $itemDetail)
    @dump($itemDetail->item_number)
    @dump($itemDetail->total_quantity)
@endforeach

答案 1 :(得分:1)

访问所需的主模型并在其中包含需要包含的关系更为有意义。

这是一个潜在的不同解决方案:

$query = Item::with(['item_details' => function ($query) {
    $query->groupBy('item_number')->selectRaw("item_number, sum(abs(a.quantity)) as 'total_quantity'");
}]);
if (isset($param['vendor'])) {
    $query->where('vendor_id', $param['vendor']);
}
$itemsPage = $query->paginate($paged);
return $pages;

您可以通过以下方式访问分页数据:

foreach ($itemsPage as $item) {
    // $item is an instance of Item
    // $item->item_details->total_quantity should have the sum of the item details
} 

答案 2 :(得分:0)

我只能因为信息太少而猜测:您的模型缺少这样的东西:

public function a()
{
    return $this->belongsTo(RelatedModel::class);
}