从关系中获取数据但收集错误

时间:2017-01-26 08:56:33

标签: laravel

我有两个表user和用户details。这有一对一的关系。

我想在user_details表中显示users表中的所有数据(名称,电子邮件,密码)以及地址和年龄。当我有如

之类的雄辩关系时,我怎么能这样做呢
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table ='users';

    protected $fillable = ['user_name', 'email', 'password'];

    public function userdetails(){
        return $this->hasOne('App\UserDetail','user_id');
    }

}

UserDetail.php

 <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class UserDetail extends Model
    {
        protected $table ='user_details';

        protected $fillable = ['user_id', 'full name', 'address', 'age'];

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

    }

也许我可以传递给我的视图并使用foreach循环它们?

{{$user->user_details->address}}

3 个答案:

答案 0 :(得分:0)

在控制器功能中,您可以像这样获取用户

$users = User::with('userdetails')->get();

在视图和视图中传递此用户变量,并在您的视图中尝试此

@foreach($users as $user)
  {{ $user->user_name }}
  {{ $user->email }}
  {{ $user->userdetails->full_name }}
  {{ $user->userdetails->address }}
  {{ $user->userdetails->age }}
@endforeach  

答案 1 :(得分:0)

您可以使用eager loading加载数据:

$users = User::with('userdetails')->get();

然后访问它:

{{ empty($user->userdetails) ? 'No address attached to this user' : $user->userdetails->address }}

答案 2 :(得分:-1)

谢谢大家,我刚查询了相关表格。所以我使用userdetails查询

控制器:

user_detail = UserDetail::with('user')->get();