我有两种类型的用户Athletes
和Teams
。我创建了3个表users
,athletes
和teams
。我将用户名和密码存储在users
表中,并将其他信息存储在athletes
和teams
表中。我想在主页上显示Athletes
和Teams
信息。
[我的用户模型如下
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['password', 'remember_token',];
protected $fillable = ['email','password','remember_token','category_id'];
public function team()
{
return $this->hasOne(Team::class);
}
public function athlete()
{
return $this->hasOne(Athlete::class);
}
}
[我的团队模型如下
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
public $guarded = [];
protected $fillable = ['first_name','last_name','user_id','how_did_find','social_media',];
public function user()
{
return $this->belongsTo(User::class);
}
}
我的运动员模型如下
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Athlete extends Model
{
public $guarded = [];
protected $fillable = ['user_id','social_media','youtube_video','website'];
public function user()
{
return $this->belongsTo(User::class);
}
}
我正在使用控制器中的以下代码。
$staff_picks = User::orderBy('id','desc')->take(10)->with('athlete','team')->get();
在运动员和团队模型中,创建一个名为user_id的列,在用户模型中,创建具有hasMany关系的两种方法,用于运动员和团队模型。登录后,获取数据为
User::where('id', 1)->with('teams', 'athletes')->first();
用户模式内部的关系可以编写如下。
teams() {
return $this->hasMany(Team::class);
}
athletes() {
return $this->hasMany(Athlete::class);
}