Anuj kumar
Anuj kumar

Reputation: 26

Laravel Has Many through relationship not working

I am new in laravel and I am facing issue with relationships. I have three tables.

asset            assetmaintenance              users
id               id                            id
name             asset_id                      name
                 inspector_id(users_id)
                 name

I want to access all users attached with asset through assetmaintenance, so I define relationship in asset model like:

    public function users(){

        return $this->hasManyThrough(TenantUser::class,AssetMaintenance::class,'asset_id','id');
    }

But the query generated by eloquent is different from what I expected:

select * from `assets` where exists (select * from `users` inner join `assets_maintenance` on `assets_maintenance`.`id` = `users`.`id` where `assets`.`id` = `assets_maintenance`.`asset_id` and `username` like ?) and `isDeleted` = ? order by `id` desc

I want relation like assets_maintenance.inspector_id= users.id but it's comparing assets_maintenance.id = user.id.

Please suggest...

Upvotes: 0

Views: 1534

Answers (2)

Avinash Rathod
Avinash Rathod

Reputation: 86

Okay try this way

first, create a method in asset model for hasMany assetmaintenance and then after create another method in model for hasOne inspector_id and to fetch all those data in one query use below code.

Assets::with('assetmaintenance','assetmaintenance.user')->get()

Upvotes: 0

Maulik Shah
Maulik Shah

Reputation: 1050

Try with the below code:

public function users(){
    return $this->hasManyThrough(TenantUser::class, AssetMaintenance::class, 'inspector_id', 'id');
}

And also try with additional parameters

For More Laravel Has-Many-Through Relationship

Upvotes: 1

Related Questions