简体   繁体   中英

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.

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">&nbsp;</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. You are using the subject_id in your scores table and your Score model has belongsTo relation to Subject Model. So, yes you can fetch the user details like this

{{$score->subject->user->name}}

You need to use belongTo relationship in score model.

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();

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>";
}

}

Post Class

public static function 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM