users
- id
- name
- company_id
companies
- id
- company_name
watched_objects
- id
- user_id
- object_id
- type
現在我想所有看過公司的用戶。
所以查詢應該長相:
SELECT
companies.*
FROM companies
JOIN watched_objects ON watched_objects.object_id = companies.id
WHERE watched_objects.user_id = 1
我應該怎樣定義的關係?
我試試這個:
class User
{
public function watched()
{
return $this->hasManyThrough('App\Company', 'App\WatchedObject', 'user_id', 'id');
}
}
但查詢是:
SELECT
companies.*,
watched_objects.user_id
FROM companies
INNER JOIN watched_objects ON watched_objects.id = companies.id
WHERE watched_objects.user_id = 1
我怎樣才能改變watched_objects.id
到watched_objects.object_id
。
我通常在這種情況下,數據庫視圖,特別是如果你要經常讀取這些數據。(我懷疑你會) –
查看是不是我要什麼存檔。這種方法使應用程序混亂,我不會混合不同的數據庫層。 –
您可以顯示您的雄辯查詢,但拍攝'返回$ this-> hasManyThrough('App \ Company','App \ WatchedObject','user_id','id') - > where('type','=' 'company');' – cssBlaster21895