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:
- Define a
chats()
relationship on theUser
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);
}
}
- 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();