如何定义关系hasManyThrough

时间:2016-09-27 18:13:58

标签: php laravel laravel-5 orm relationship

我有桌子:

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

2 个答案:

答案 0 :(得分:1)

如果您将object_id视为公司ID,则该关系被视为多对多。然后表watched_objects将是保持用户和公司关系的第三个表。

class User {
    public function watched() {
        return $this->belongsToMany('App\Company', 'watched_objects', 'user_id', 'object_id');
    }
}

为了找到用户1的受监控公司,您可以使用以下代码。

$watched_companies = User::find(1)->watched;

答案 1 :(得分:0)

要获得用户观看所有公司,您可以这样做:

$watches=WatchedObject::where(['user_id'=>Auth::user()->id])->with('company')->get();
foreach($watches as $watch)
{
     print_r($watch->company->company_name);
}    

<强>关系: 公司有许多观看对象:

public function watches()
{
    return $this->hasMany('App\WatchedObject','object_id'); 
}

并且属于watchedObject Model:

public function company()
{
    return $this->belongsTo('App\Company','object_id');
}