[英]How to get the data from 3 tables with one to many relation
I have table named SCORES , then inside has foreign key named subject_id which relationship is one to many from table named SUBJECTS then inside table SUBJECTS has foreign key also named user_id which relationship is one to many from table named USERS , now I was able to show the list of subject from SCORES table now how to get the username who's subject_id is equal to user_id. 我有一个名为SCORES的表,然后内部有一个名为subject_id的外键,该关系与名为SUBJECTS的表是一对多的关系,然后在表SUBJECTS中有一个外键也叫user_id,其关系与名为USERS的表是一对多的关系,现在我可以显示现在从SCORES表中获取主题列表,如何获取subject_id等于user_id的用户名。
Controller: 控制器:
$scores = Score::with('lead','subject')->where('lead_id','=',$id)->get();
$subjects=Subject::with('user')->get();
View 视图
<tr>
@foreach($scores as $score)
<th><font size="1"> </font></th>
@endforeach
</tr>
<tr>
@foreach($scores as $score)
<td>
<font size="1">{{$score->subject->subject_name}}</font>
@endforeach
</td>
</tr>
From chat discussion it found that you have belongsTo
relation between Subject
and User
model. 从聊天讨论中,您发现您在
Subject
和User
模型之间具有belongsTo
关系。 You are using the subject_id
in your scores table and your Score
model has belongsTo
relation to Subject
Model. 您正在使用分数表中的
subject_id
,并且您的Score
模型具有与Subject
模型的belongsTo
关系。 So, yes you can fetch the user details like this 因此,是的,您可以像这样获取用户详细信息
{{$score->subject->user->name}}
You need to use belongTo
relationship in score model. 您需要在分数模型中使用
belongTo
关系。
public function user(){
return $this->belongsTo(User::class,'subject_id ');
}
Now you can get user name something like this. 现在您可以获取类似这样的用户名。
$scores = Score::with('lead','subject')->with('user')->where('lead_id','=',$id)->get();
$posts = Posts::read_all();
foreach ( $posts as $post )
{
echo $post->post_name ."<br>";
echo $post->post_text ."<br>";
$categories_array = Posts::get_cats_by_post_id($post->id);
foreach ($categories_array as $category)
{
echo "•". $category->category_name ."<br>";
}
} }
public static function get_cats_by_post_id($id) { $db = new Database(); 公共静态函数get_cats_by_post_id($ id){$ db = new Database();
$sql = "SELECT cats_to_posts.cats_id
FROM cats_to_posts
WHERE cats_to_posts.post_id = {$id}";
$result = $db->exe_query($sql);
$cat_id_array = array(); // stores array of category ids that match post ids
while ( $record = $result->fetch_object() )
{
$cat_id_array[] = $record;
}
$cat_name_array = array(); // stores array of category names that match category ids
foreach($cat_id_array as $cat_id)
{
$new_sql = "SELECT category_name
FROM categories
WHERE id = ". $cat_id->cats_id;
$new_result = $db->exe_query($new_sql);
while ( $new_record = $new_result->fetch_object() )
{
$cat_name_array[] = $new_record;
}
}
return $cat_name_array;
} }
Try this Hope so this will work. 试试这个希望,这样就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.