I went through multiple examples and previous posts here, but I can't find what I am doing wrong. I have two tables:
Users
id username
1 test1
2 test2
3 test3
Scores table
id user_id points
1 1 52
2 2 62
3 3 12
And now I want to get all scores and replace user_id with actual username. Here is my code:
ScoresController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Score;
use App\Http\Resources\Score as ScoreResource;
class ScoresController extends Controller
{
public function index()
{
$scores = Score::with('user')->paginate(4);
return ScoreResource::collection($scores);
}
}
Score.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Score extends Model
{
public function user(){
return $this->belongsTo(User::class,'user_id');
}
}
User
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Score;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $fillable = [
'username', 'email', 'password', 'avatar'
];
protected $hidden = [
'password', 'remember_token',
];
public function scores(){
return $this->hasMany(Score::class,'user_id');
}
}
And Score resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Score extends JsonResource
{
public function toArray($request)
{
return [
'username' => $this->user_id,
'points' => $this->points,
];
}
}
At the moment I am showing user_id and points, I tried with
$this->username OR $this->user-id->username
but none of them works and I know I could use DB or raw SQL, but I want to do it this way
Read this: https://laravel.com/docs/5.7/eloquent-relationships
foreach ($scores as $score) {
echo $score->user->username;
}
Or in Blade:
@foreach ($score as $score)
<p>{{ $score->user->username }}</p>
@endforeach
You must first access the 'property' which is the name you defined the function that handles the relationship. In your case that is user
.
After that, you will be returned the User
class for that user, where you can then access any properties you like.
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.