簡體   English   中英

如何從具有一對多關系的3個表中獲取數據

[英]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">&nbsp;</font></th> 
  @endforeach 
</tr>

<tr>
  @foreach($scores as $score)
 <td>
   <font size="1">{{$score->subject->subject_name}}</font>
  @endforeach 
 </td>
</tr>

從聊天討論中,您發現您在SubjectUser模型之間具有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();

的index.php

      $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 "&bull;". $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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM