简体   繁体   中英

Laravel: hasMany get values from parent table also

I am a student and new in laravel.

I am using hasmany its working fine but its only showing me the result of attendance table for exampble in user table George have 5 entries in attendance table its working fine but i also want to show the name of user and all details of user which is available in user table

below is my code:

AttendanceController:

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

Attendance Model:

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

result:

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

Your attendance relationship model is wrong, it should be in a relation with user model class and not with itself like you currently have:

Attendance Model:

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

Should be pointing to user model:

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

Since when u eager load the user it should return user data also.

Your relationship is wrong. It should be a User hasMany attendances and not the other way round.

Attendance Model:

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

User Model:

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

Then with your $userId , do this:

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

In response to your question:

I suppose you already have your $userId right?. In your UserController, you can do:

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

Let's assume you want to use it in your view. Then do this:

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

In your view, do this:

<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>

You can check here for more insight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM