Laravel:hasMany 也从父 table 获取值

Laravel: hasMany get values from parent table also

我是 laravel 的学生。

我正在使用 hasmany 它工作正常但它只显示出勤结果 table 例如在用户 table George 有 5 个条目参加 table 它工作正常但是我还想显示用户名和用户的所有详细信息 table

下面是我的代码:

考勤控制器:

 $attendance = Attendance::with('users')->WhereIn('aid',$arr)->get();

出勤模式:

public function users()
{
    return $this->hasMany('App\Attendance','aid','aid');
}

结果:

{
    "id": 1,
    "aid": 1,
    "date_in": "2018-08-03",
    "start": "09:27:00",
    "end": "18:27:00",
    "time_long": "08:59:00",
    "created_at": "2018-08-23 06:39:27",
    "updated_at": "2018-08-23 06:39:27",
    "users": [
        {
            "id": 1,
            "aid": 1,
            "date_in": "2018-08-03",
            "start": "09:27:00",
            "end": "18:27:00",
            "time_long": "08:59:00",
            "created_at": "2018-08-23 06:39:27",
            "updated_at": "2018-08-23 06:39:27"
        }
    ]
}

你的出勤关系模型是错误的,它应该是与用户模型class的关系,而不是像你现在这样与自己的关系:

出勤模式:

public function users()
{
    return $this->hasMany('App\Attendance','aid','aid');
}

应该指向用户模型:

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

因为当你急切加载用户时它也应该 return 用户数据。

你的关系不对。它应该是一个 User hasMany attendances 而不是相反。

出勤模式:

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

用户模型:

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

然后用你的$userId,这样做:

$attendances = App\User::find($userId)->attendances;

回答您的问题:

我想你已经有了你的 $userId 了吧?。 在您的 UserController 中,您可以执行以下操作:

$user = User::find($userId);    //Find the user that has that id

假设您想在您的视图中使用它。然后这样做:

return view('view-name', ['user' => $user]);    //pass $user to view

在您看来,这样做:

<ul>
    @foreach($user->attendances as $attendance)      <!--$user->attendances - You remember this?-->
        <li>{{ $user->name }} came to work on {{ $attendance->id }}</li>     <!--$user->name, $attendance->id - You can always get any other user/attendance attribute you want-->
    @endforeach
</li>

您可以查看 here 以获得更多信息。