I need to know the Laravel Eloquent syntax for querying the nested relationship and returning the results

Shane Poppleton :

I have the following models

  • Company
  • Contact
  • Ticket
  • Job
  • User

Job BelongsTo Ticket, Ticket BelongsTo Contact or User (Polymorphic), Contact Belongs to Company. I can retrieve all jobs for a particular company with

Company::with('contacts.tickets.jobs')->where('id', 10)->get();

I want a list of all the jobs in the system for a particular company. I have tried the following, but it's not working, it is returning all Jobs

Job::with(['ticket' => fn($b) => $b->whereHasMorph('creator', [App\Contact::class],fn($b) => $b->where('company_id', 10))])->get();
Jax Terra :
$companyId = 6;

Job::whereHas('ticket', fn($b) => 
    $b->whereHasMorph('creator', [App\Contact::class], fn($c) => 
        $c->where('company_id', $companyId)
    )
   )->with(['ticket.creator.company'])->get();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12453&siteId=1