Home > Blockchain >  Laravel query builder where on eloquent relation
Laravel query builder where on eloquent relation

Time:08-17

I have 3 tables:

  • users,
  • jobs: id,user_id,name
  • chats: id,job_id,name

I want to get chats depends on user's job. i've tried this one below, but i still get data from all chat, for example i want to get chat's data from user_id = 3:

$chat = Chat::with(['jobs' => function($query) use($userId){
                    $query->where('user_id',$userId);
}])->get();

CodePudding user response:

  1. Define a chats() relationship on the User model.
<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * Get all the chats for the user.
     */
    public function chats()
    {
        return $this->hasManyThrough(Chat::class, Job::class);
    }
}

  1. Get chat data from user_id = 3.
$userId = 3;

User::query()->with(["chats"])->find($userId);

Resource: Has Many Through

CodePudding user response:

You need to use whereHas instead of with

WhereHas: Constraints your results based on the relationship query

$chat = Chat::whereHas('jobs', function($query) use($userId){
                    $query->where('user_id',$userId);
})->get();

With: Load the giving relationship in the same query

you can use both to load the relationship and constraint the result:

$chat = Chat::with(['jobs'])
->whereHas('jobs', function($query) use($userId){
      $query->where('user_id', $userId);
})->get();
  • Related