我有以下表用户表,帖子表和配置文件表。帖子属于用户,个人资料属于用户。我也有一个论坛,人们可以发帖我希望用户的用户名显示而不是他们的名字。但是用户名在个人资料表中,我不知道如何获取它。
这是我的代码
class Post extends Model
{
//
public function users(){
return $this->belongsToMany('App\User','posted_by');
}
class Profile extends Model
{
//
public function users(){
return $this->belongsTo('App\User','whos_profile');
}
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'firstname','lastname', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profile(){
return $this->hasOne('App\Profile');
}
public function post(){
return $this->hasMany('App\Post');
}
}`enter code here`
答案 0 :(得分:0)
您可以按照以下方式获取
$user = User::find($id);
if($user->profile){
echo $user->profile->username;
}
答案 1 :(得分:0)
你应该试试这个:
$rsltUsers = User::with(['profile','post'])->where('id',$id)->get();
foreach($rsltUsers as $rsltUsers){
dd($user->profile->username);
}