简体   繁体   English

HasManyThroug 关系返回 SQL 错误

[英]HasManyThroug relations is returning SQL error

I am working on an internal PMS, where I have four models: User , Company , Client and Project .我正在研究一个内部 PMS,我有四个模型: UserCompanyClientProject

One Company will have multiple Users , and through the Company , the User will have access to many Clients and Projects .一家Company将有多个Users ,并且通过CompanyUser将可以访问许多ClientsProjects Nothing fancy here, just a classic PMS with company, clients, users and projects.这里没有什么特别的,只是一个与公司、客户、用户和项目有关的经典 PMS。

The User model has a company_id field (one user can only be related to one company at the moment). User model 有一个company_id字段(一个用户目前只能与一个公司相关)。 The Client model also has a company_id field. Client model 也有一个company_id字段。 With this I thought I could have a HasManyThrough relationship for User and Client , and I tried this:有了这个,我认为我可以为UserClient建立HasManyThrough关系,我尝试了这个:

public function clients()
{
    return $this->hasManyThrough( Client::class, Company::class );
}

However, this returns the但是,这将返回

SQLSTATE[HY000]: General error: 1 no such column: companies.user_id (SQL: SQLSTATE[HY000]:一般错误:1 没有这样的列:company.user_id (SQL:

 select "clients".*, "companies"."user_id" as "laravel_through_key" from "clients" inner join "companies" on "companies"."id" = "clients"."company_id" where "companies"."user_id" = 1 and "clients"."deleted_at" is null

In my database, companies.user_id doesn't exist, because this relation is defined by users.company.id .在我的数据库中, companies.user_id不存在,因为这个关系是由users.company.id定义的。 Would it be better to write a raw SQL query?写一个原始的 SQL 查询会更好吗?

Or may just use two relations like:或者可以只使用两个关系,例如:

// User Model
[.....]
public function company()
{
    return $this->belongsTo( Company::class, [YOUR_FK_HERE] );
}

public function clients()
{
    return $this->company->clients();
}
[....]

and in the Company Model并在公司 Model

// Company Model
[....]
public function clients()
{
    return $this->hasMany( Client::class, [YOUR_FK_HERE] );
}
[....]

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

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