$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
WhereHas
whereHas()的工作原理与has()基本相同,但允许你为相关的模型指定额外的过滤器进行检查。
例子:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
// App\Models\Order:
public function orderItems() {
return $this->hasMany('App\Models\OrderItem', 'order_id', 'id');
}
这三个方法是一切都基于一段关系。
与
结果:with()返回模型对象及其相关结果。
优势:它是立即加载,可以防止N+1问题。
当你使用以下雄辩的建设者:
Order::with('orderItems')->get();
Laravel将此代码更改为只有两个SQL:
// get all orders:
SELECT * FROM orders;
// get the order_items based on the orders' id above
SELECT * FROM order_items WHERE order_items.order_id IN (1,2,3,4...);