簡體   English   中英

Laravel:hasMany還從父表獲取值

[英]Laravel: hasMany get values from parent table also

我是一名學生,也是laravel的新手。

我正在使用hasmany,它的工作正常,但僅向我顯示用戶表中考勤表的結果,喬治在工作表中有5個條目,其工作正常,但我也想顯示用戶名和可用的所有用戶詳細信息在用戶表中

下面是我的代碼:

AttendanceController:

 $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"
        }
    ]
}

您的出勤關系模型是錯誤的,它應該與用戶模型類有關系,而不是與您當前擁有的類有關:

出勤模式:

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

應該指向用戶模型:

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

因為當您加載用戶時,它也應該返回用戶數據。

你的關系是錯的。 應該是用戶有很多出席,而不是相反。

出勤模式:

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>

您可以在此處查看更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM