Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deekshith's avatar

How to add relationship for three tables.

Hello, i have three tables,

orders

id, user_id, txn_id, amount, date, course_id

user_roll_numbers

id, user_id, roll_no,course_id

courses

id, course_name, description, cost

Here the flow will be like below,

  1. user will select the available courses and purchase the course.
  2. On purchase data will be inserted to orders table.
  3. Along with order data roll number data will be inserted to user_roll_numbers table with course_id and user_id .
  4. Now i am trying to fetch all orders data with roll number and course details.

In Orders.php i have code like below,

public function coursedetail()
    {
      return $this->belongsTo('App\Courses','course_id','course_id');
    }

public function usermydetail()
    {
      return $this->belongsTo('App\User','user_id','user_id');
    }

i am getting course details and user details but i want to fetch user roll number too which i should match user_id and course_id of orders table with user_roll_numbers table. any idea on how to do this?

i have tried code like below,

$orderdetails = Orders::with('usermydetail')->with('coursedetail')->where('orders.course_id',$courseid)->where('orders.activation_type','=','PAID')->inRandomOrder()->take(10)->get();

I want to fetch user_roll_numbers table data too which should match course_id and user_id of orders table. how to do this?

0 likes
1 reply

Please or to participate in this conversation.