简体   繁体   English

laravel Auth :: user() - >返回所有不仅仅是经过身份验证的用户

[英]laravel Auth::user()->with return all not just authenticated user

wrong: this return all Users with their persons: 错误:这将所有用户与其人员一起返回:

$me = Auth::user()->with('persons')->get();

correct: this return just the authenticated user with his persons 正确:这只返回经过身份验证的用户和他的人员

Auth::user()->persons()->get()

Model 模型

 public function persons(){
        return $this->hasMany('App\Person', 'user_id');
    }

where is the difference? 区别在哪里? why first line returns ALL users? 为什么第一行返回所有用户?

thanks 谢谢

with is supposed to be called on a Builder object non on a Model instance. with应该在被称为Builder一个模型实例对象非。

In the first example, you're calling it on a User instance, that is like calling: 在第一个示例中,您在User实例上调用它,就像调用:

User::with('persons')->get();

so Laravel returns all users along with their persons 所以Laravel会将所有用户及其人员一起返回

Note that if you want to load a relation on a single model you can do: 请注意,如果要在单个模型上加载关系,可以执行以下操作:

$me = Auth::user();
$me->load('persons');

The use of ->with() in query builder is to eager load the relation so it loads related models. 在查询构建器中使用->with()急切加载关系,以便加载相关模型。 It does not return the related models, only loads them. 返回相关模型,只加载它们。

One interesting thing to note here is that auth()->user(), return User model instance. 这里要注意的一件有趣的事情是auth() - > user(),返回User模型实例。 Hence, when chaining it with ->with('persons')->get() you're essentially creating a new Query Builder. 因此,当使用->with('persons')->get()您实际上是在创建一个新的Query Builder。

$user = auth()->user();
// The following line creates new Query for User model
$allUsersWithPersons = $user->with('persons')->get();
// same as following line
$allUsersWithPersons2 = User::with('persons')->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM