Laravel's query builder provides the whereRelation
method, which is very useful for querying relationships.
Here's the syntax for using the whereRelation
method:
Model::whereRelation('relation', 'column', 'operator', 'value')
// or, using the default (=) operator
Model::whereRelation('relation', 'column', 'value')
Suppose there is an Order
model that has a hasMany
relationship with the OrderItem
model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
public function items() {
return $this->hasMany(OrderItem::class);
}
}
Now, let's say we want to get all orders that have items with a quantity greater than 100. This can be done using the whereRelation
method. For example:
$ordersWithMinimumItemQty = Order::whereRelation('items', 'quantity', '>', 100)
->get();
Behind the scenes, the whereRelation
method actually calls the whereHas
method. For example:
$ordersWithMinimumItemQty = Order::whereRelation('items', 'quantity', '>', 100)
->get();
// Equivalent to using whereHas:
$ordersWithMinimumItemQty = Order::whereHas('items', function ($query) {
$query->where('quantity', '>', 100);
})->get();
As you can see, whereRelation
simplifies the use of the whereHas
method.
Top comments (0)