[英]How to get the data from 3 tables with one to many relation
我有一個名為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>
從聊天討論中,您發現您在Subject
和User
模型之間具有belongsTo
關系。 您正在使用分數表中的subject_id
,並且您的Score
模型具有與Subject
模型的belongsTo
關系。 因此,是的,您可以像這樣獲取用戶詳細信息
{{$score->subject->user->name}}
您需要在分數模型中使用belongTo
關系。
public function user(){
return $this->belongsTo(User::class,'subject_id ');
}
現在您可以獲取類似這樣的用戶名。
$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>";
}
}
公共靜態函數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;
}
試試這個希望,這樣就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.