简体   繁体   English

Laravel 有很多通过关系不起作用

[英]Laravel Has Many through relationship not working

I am new in laravel and I am facing issue with relationships.我是 laravel 的新手,我面临着人际关系问题。 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:我想通过assetmaintenance访问附加资产的所有用户,所以我在资产模型中定义了关系,如:

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:但是eloquent生成的查询和我预想的不一样:

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 .我想要像assets_maintenance.inspector_id= users.id这样的关系,但它正在比较assets_maintenance.id = user.id

Please suggest...请建议...

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欲了解更多Laravel 的通道关系

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.首先,在资产模型中为 hasMany assetmaintenance 创建一个方法,然后在模型中为 hasOne inspector_id 创建另一个方法并在一个查询中获取所有这些数据,使用下面的代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM