Laravel 5关系很多,有两个表

时间:2017-10-24 13:08:37

标签: mysql laravel-5 laravel-eloquent

我试图通过数据透视表在同一个表上建立关系。 我有两个表:companies(id)和一个表company_budgets(id,company_id,sponsor_id,budget)。 我需要以下关系:

  • 公司表中的公司可以赞助公司表中的多家公司
  • 公司表中的公司可以有多家公司表赞助商

我尝试了不同的变体

public function sponsors() {
  return $this->belongsToMany('App\Company','company_sponsors','company_id','sponsor_id')->withPivot('budget');
}

public function companies() {
  return $this->belongsToMany('App\Company','company_sponsors','sponsor_id','company_id')->withPivot('budget');
}

但是...

接下来的问题是如何从数据透视表中检索数据? 如何查询公司是否获得赞助以及公司如何赞助?

我想查询我的表格:

SELECT
companies.id AS "Company ID",
companies.`name` AS "Sponsoring company name",
company_sponsors.sponsor_id AS "Sponsored company ID",
(SELECT companies.`name` FROM companies WHERE companies.id = sponsor_id) AS "Sponsored company",
company_sponsors.budget AS "Sponsored budget"
FROM company_sponsors
INNER JOIN companies ON companies.id = company_sponsors.company_id
WHERE companies.id = 33;


SELECT
companies.id AS "Company ID",
companies.`name` AS "Sponsored company name",
company_sponsors.company_id AS "Sponsor ID",
(SELECT companies.`name` FROM companies WHERE companies.id = company_id) AS "Sponsor company name",
company_sponsors.budget AS "Sponsoring budget"
FROM companies
LEFT JOIN company_sponsors ON company_sponsors.sponsor_id = companies.id
WHERE companies.id = 10;

0 个答案:

没有答案