M
M
muhasa2020-09-13 02:17:23
Laravel
muhasa, 2020-09-13 02:17:23

To many via laravel eloquent - how to make a tricky request?

Hello.
There are 3 tables - doctors, clients, ClientCourse, as a connection between a client and a certain course in the system.

*client_course*
id
name
doctor_id
client_id


That is, the doctor is assigned to a specific course, and is not assigned to the client.
How to connect the link so that inside the doctor model you can hook all the clients assigned to the courses?
I tried like this
public function clients()
    {
      return $this->hasManyThrough('App\Client', 'App\ClientCourse');
    }

what did you get
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'clients.client_course_id' in 'on clause' (SQL: select `clients`.*, `client_course`.`doctor_id` as `laravel_through_key` from `clients` inner join `client_course` on `client_course`.`id` = `clients`.`client_course_id` where `client_course`.`doctor_id` = 1)


What am I doing wrong?..

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kami16ru, 2020-09-13
@kami16ru

on `client_course`.`id` = `clients`.`client_course_id`
You obviously made a mistake here.
public function clients()
{
return $this->hasManyThrough('App\Client', 'App\ClientCourse');
}
You have a many-to-many relationship, just hasMany(Client::class)

J
jazzus, 2020-09-14
@jazzus

Choice:

public function clients()
{
    return $this->hasManyThrough(
        Client::class, 
        ClientCourse::class,
        'doctor_id',
        'id',
        'id',
        'client_id'
    );
}

public function clients()
{
    return $this->belongsToMany(Client::class, 'client_courses');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question