Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

php - Eloquent query returning different objects?

I'm running into an error i've never seen before and don't know what is going on. Running the following code will get a collection of users. Each element is an instance of the user model as expected but just with the columns selected:

$users = User::where('xyz', 123)->select('columns')->get()

Let's say the above code returns multiple users. The developer is looping through the users collection and is running this (not the best way, i know, but debugging another devs code):

$users->each(function($user) { 
    User::find($user->id)->user_model_method()->each(...); 
});

I'd prefer to do this so i'm not running a query for data I already have but I can't figure out why the user_model_method is returning no results for this code (I realize I could potentially do some lazy loading):

$users->each(function($user) { 
    $user->user_model_method()->each(...); 
});

I've dd() the User::find($user->id) and $user and each are instances of the same model and they both represent the same user record in the db so I don't know why User::find($user->id) returns results for the user_model_method but $user doesn't. What am I missing? It seems like $user isn't a complete instance of the User model or something weird but the method still exists on it.

EDIT: dd() the $users collection gives me this:

IlluminateDatabaseEloquentCollection^ {#4331
  #items: array:10 [
    0 => AppModelsUser^ {#2664
      ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...