本文介绍了在Laravel中显示2种数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两种类型的用户Athletes
和Teams
.我创建了3个表users
,athletes
& teams
.我正在存储用户名& users
表中的密码和athletes
&中的其他信息; teams
表.我想在主页中显示Athletes
和Teams
信息.
I have 2 types of user Athletes
and Teams
. I created 3 tables users
,athletes
& teams
. I am storing username & password in users
table and others information in athletes
& teams
table. I would like to display Athletes
and Teams
information in home page.
我的用户模型如下所示
<?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);
}
}
我在控制器中使用以下代码.
I am using below code in controller.
$staff_picks = User::orderBy('id','desc')->take(10)->with('athlete','team')->get();
推荐答案
应该是这样
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);
}
}
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);
}
}
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();
和迭代
foreach($staff_picks as $r){
$r->teams->social_media; //(user can be either teams or athletes so must check for null)
$r->athletes->social_media; //(user can be either teams or athletes so must check for null)
}
这篇关于在Laravel中显示2种数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!