我有一个名为 SCORES 的表,然后内部有一个名为subject_id的外键,该关系与名为 SUBJECTS 的表之间是一对多的关系,然后是在表 SUBJECTS 中>有一个外键,也名为user_id,它与名为 USERS 的表是一对多的关系,现在我能够显示 SCORES 表中的主题列表,现在该如何获取用户名的subject_id等于user_id。
控制器:
$scores = Score::with('lead','subject')->where('lead_id','=',$id)->get();
$subjects=Subject::with('user')->get();
查看
<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>
答案 0 :(得分:1)
从聊天讨论中发现,belongsTo
和Subject
模型之间具有User
关系。您正在分数表中使用subject_id
,并且您的Score
模型与belongsTo
模型具有Subject
关系。因此,是的,您可以像这样
{{$score->subject->user->name}}
答案 1 :(得分:0)
您需要在分数模型中使用belongTo
关系。
public function user(){
return $this->belongsTo(User::class,'subject_id ');
}
现在您可以获得类似这样的用户名。
$scores = Score::with('lead','subject')->with('user')->where('lead_id','=',$id)->get();
答案 2 :(得分:0)
$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>";
}
}
公共静态函数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;
}
尝试一下 希望这会起作用。