简体   繁体   中英

Select from table 1 with foreign_key = x on table 2 where table 2 foreign key = Y on table 3

Not sure if the title makes much sense, but here is a better description: I have a table of shifts that have an id for the shift worker and an id for the client the shift worker does something for, and the clients table has a user id with associated record in users table.

I would like to select all shifts that have a client id where the associated user id on the client record is X.

Shifts Table
shift_id
shiftworker_id
client_id
...

Clients Table
client_id
user_id
...

Users Table
user_id
...

So, I want all the records (from shifts) where the client_id for the shift belongs to a specific user.

User has many clients, and client has many shifts associated with it. I think what I am after is some kind of join like this:

select * from shifts join shifts.client_id on clients.id and where clients.user_id = X

I am trying to do this in Laravel, like:

DB::table('shifts')->join('clients', 'client_id', '=', ...)->join('users', 'client_id', '=', X);

Although any help with the SQL is appreciated and I can figure out the Laravel query from there.

Thank you

The easiest way will be to create a "has many through relationship" and query the User model with "user id" instead of querying shifts.

class User extends Model
{
    public function shifts()
    {
        return $this->hasManyThrough(Shift::class, Client::class);
    }
}
class ShiftController extends Controller
{
    public function index()
    {
         return User::where('id', 1)->with('shifts')->first()->shifts;
    }
}

If it works, the controller code will return the records from the shifts table without any relational data or extra fields. If you need to add some extra fields, this method might not be the best one. In this case, give more details about the desired output data.

UPDATE AFTER THE COMMENT

You don't need to use any eloquent relation function to get shift data per client, because client_id is already on the shift tables. All you need is:

Shift::where('client_id', $client_id)->get();

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