我试图通过数据透视表在同一个表上建立关系。
我有两个表: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;