doutu1939 2019-04-14 14:15
浏览 14

如何使用laravel 5.7中的eager-load从子模型的外键实例中获取父值

i have four models -User -Question -Answer -Comment

the User model contains

public function questions(){
        return $this->hasMany(Question::class);
 }
public function answers(){
        return $this->hasMany(Answer::class);
}
public function comments(){
        return $this->hasMany(Comment::class);
}

the Question model contains

public function users(){
        return $this->belongsTo(User::class,'user_id','id');
}
public function answers(){
        return $this->hasMany(Answer::class);
}
public function comments(){
        return $this->hasMany(Comment::class);
}

//the question table has user_id

the Answers model contains

public function questions(){
        return $this->belongsTo(Question::class,'user_id','id');
}
public function users(){
        return $this->belongsTo(User::class);
}
public function comments(){
        return $this->hasMany(Comment::class);
}

//the answers table has user_id,question_id

the Comment model contains

public function questions(){
        return $this->belongsTo(Question::class);
}
public function users(){
        return $this->belongsTo(User::class);
}
public function answers(){
        return $this->belongsTo(Answer::class);
}

//the answers table has user_id,question_id,answer_id

whenever access the Question model i can get access User,Answer,Comment related to that Question

but i want to get the details of the user that answers the question as well as the details of the user that commented on an answer.

this is my controller

public function show($slug){    
        $questionData = Question::with('users','answers','comments')->where('slug',$slug)->first();
         return view('questions.single',compact('questionData'));
}

but wheneva i do

@foreach($questionData->answers as $answer)
    $answer->user_id;
   //it retuns only the user_id from the answers table
   //how can i turn this to the username
@endforeach

i want to get the username of the user who answerd the question, as well as the username of the user that commented on the answer

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 公交车和无人机协同运输
    • ¥15 stm32代码移植没反应
    • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
    • ¥100 连续两帧图像高速减法
    • ¥15 组策略中的计算机配置策略无法下发
    • ¥15 如何绘制动力学系统的相图
    • ¥15 对接wps接口实现获取元数据
    • ¥20 给自己本科IT专业毕业的妹m找个实习工作
    • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
    • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)