查询生成器 returns 数组而不是集合

query builder returns array instead of collection

User.php(用户模型)

class User extends Authenticatable
{
  public function profiles(){
        return $this->hasOne('App\Profile');
    }
}

Profile.php(资料模型)

class Profile extends Model
{
  public function users(){
        return $this->belongsTo('App\User');
    }
}

要查看 returns 数据的函数:

public function show_users(){
    $users = User::where('id','!=',Auth::user()->id)->get();
    return view('pages.show_users')->withUsers($users);
}

show_user.blade.php(查看)

@foreach($users as $user)
   {{$user->profile->first_name}} //Gives error:Trying to get property of non-object
   {{$user->profiles['first_name']}} // Gives desired result
@endforeach

为什么返回的结果是数组而不是集合?

返回的结果确实是一个集合。这只是一个错字问题

您在 profiles

中忘记了一个 s
{{ $user->profiles->first_name }}

另请注意,即使您这样访问 first_name

{{ $user->profiles['first_name'] }}

这并不意味着它不是一个集合。

如果您查看 Illuminate\Database\Eloquent\Model.php 的源代码,您会发现它实现了一些很酷的功能,例如 offsetGetoffsetSetoffsetExists

这里有更多信息。 PHP ArrayAccess

您收到该错误的原因是因为

有些用户可能没有个人资料。因此在空对象的配置文件上调用 first_name 将引发错误。

你能做的就是php7你能做的

@foreach($users as $user)
    {{$user->profiles->first_name ?? 'No first name'}}
@endforeach

php 5.6 及以下

@foreach($users as $user)
    @if($user->profiles->isNotEmpty())
       {{$user->profiles->first_name}}
    @else
       No name
    @endif
@endforeach

此外,为什么不使用预先加载来加载您的配置文件以获得性能优势。您的查询现在将产生 N+1 查询问题。

您可以将查询更改为

public function show_users()
{
   $users = User::with('profiles')->where('id','!=',Auth::user()->id)->get();
   return view('pages.show_users')->withUsers($users);
}

希望对您有所帮助