Laravel 5.3限制急切负载无法正常工作 [英] Laravel 5.3 Constraining Eager Loads not working

查看:70
本文介绍了Laravel 5.3限制急切负载无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型UserProfile一对一.

I have two model User and Profile in one to one relationship.

我想使用以下代码在profile.status == TRUE中检索所有用户.

I want to retrieve all user where profile.status == TRUE using following code.

$users = User::with(['profile' => function ($query) {
        $query->where('status', TRUE);
    }])->get();


    dd(count($users)); //50 

我有50个用户,其中只有3个具有status == TRUE.但始终会显示 50 .

I have 50 users and only among of them only 3 has status == TRUE. But always it display 50.

推荐答案

您正在获取50个用户,因为您正在对profile应用条件. dd($user->profile)您将只获得状态为true的配置文件的记录.

You are getting 50 users because you are applying condition to profile. dd($user->profile) you will get only the records of the profile whose status is true.

使用whereHas():

$users = User::whereHas('profile', function ($query) {
        $query->where('status', TRUE);
    })->get();

dd(count($users));

这篇关于Laravel 5.3限制急切负载无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆