Adam Lambert
Adam Lambert

Reputation: 1421

Laravel relationships - whereHas on hasMany

1 entry in my delivery table is related to:

Delivery has:

public function deliveryItems()
{
    return $this->hasMany(DeliveryItem::class);
}

public function stockMovements()
{
    return $this->hasMany(StockMovement::class,'entity_id');
}

DeliveryItem has:

public function stockMovements()
{
    return $this->hasMany(StockMovement::class, 'product_id', 'product_id')
        ->where('entity_id', $this->delivery_id);
}

The deliveryItems table contains a list of items that are due on the delivery and the stockMovements table contains what is due and what has been received. There is a situation where I may have a line in my deliveryItems table but no correlating line in the stockMovements. I am trying to get a collection of these items.

I have tried things like:

$delivery->deliveryItems()->whereHas('stockMovements')->get() //returns empty collection. Can use whereNotHas to get the opposite if it worked.

^^ This above returns an empty collection.

foreach($delivery->deliveryItems as $item){
    dump($item->whereHas('stockMovements')->get());
}

^^ This seems to produce the correct result but produces the same result for each of the loops. I don't believe I need the foreach but am unsure hot to get it working without it! I think I need to run the whereHas directly on the deliveryItems collection but am unable to work out how to.

Upvotes: 3

Views: 5534

Answers (2)

rkj
rkj

Reputation: 8287

can you try this

$delivery = Delivery::with(['deliveryItems' => function($query){
                  $query->doesntHave('stockMovements');
              }])->find($deliveryId);

dd($delivery->deliveryItems);

Upvotes: 2

Mahbub
Mahbub

Reputation: 4932

You may try by removing where('entity_id', $this->delivery_id) condition in relationship method of DeliveryItem model.

public function stockMovements()
{
    return $this->hasMany(StockMovement::class, 'product_id', 'product_id');
}

Upvotes: 2

Related Questions