且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel关系HasOneThrough

更新时间:2023-12-04 08:19:58

已编辑-由于您需要start_date和end_date,因此您只能认为这很明显,该当前属性的最后一个条目是活动条目.因此,我相信这不是处理HasManyThrough的好方法,而是处理所有可能情况的更好方法:)

Edited - Since you require the start_date and end_date, you can only consider this obvious that the last entry for that current property is the active one. Therefore, instead of going for a HasManyThrough, I am sure this will be a better approach for handling all kinds of cases possible :)

landlords
id | landlord_name
---|--------------
1  |   landmine1
2  |   landmine2

tenants
id | tenant_name
---|--------------
1  |    haha
2  |    hehe
3  |    hoho

properties
id | property_name | 
---|---------------|
1  |   abc         |
2  |   abcd        |
3  |   abcde       |

landlord_property
id | property_id | landlord_id | start_date | end_date
---|-------------|-------------|------------|---------
1  |   1         |    1        |  SomeDate  | SomeDate
2  |   1         |    2        |  SomeDate  | SomeDate
3  |   2         |    1        |  SomeDate  | SomeDate

property_tenant
id | property_id | tenant_id   | start_date | end_date
---|-------------|-------------|------------|---------
1  |   1         |    1        |  SomeDate  | SomeDate
2  |   2         |    1        |  SomeDate  | SomeDate
3  |   1         |    2        |  SomeDate  | SomeDate

在这种情况下,不需要中间/数据透视表

There is no need of intermediate/pivot table in this case

class Property extends Model
{
  public function landlords()
  {
    return $this->belongsToMany('App\Landlord');
  }

  public function tenants()
  {
    return $this->belongsToMany('App\Tenant');
  }
}

class Tenant extends Model 
{
  public function properties()
  {
    return $this->belongsToMany('App\Property');
  }

  public function landlord()
  {
    return $this->belongsTo('App\Landlord');
  }
}

class Landlord extends Model
{
  public function properties()
  {
    return $this->belongsToMany('App\Property');
  }

  public function tenants()
  {
    return $this->hasMany('App\Tenant');
  }
}

现在您可以轻松地进行

$landlord = Landlord::find(1);
$propertiesOfLandlord = $landlord->properties;

$tenantsOfProperty = collect();

foreach($propertiesOfLandlord as $property) {
  $currentTenant = $property->tenants->last();
  if($currentTenant) {        
    $tenantsOfProperty->push($currentTenant);
  }
}

$property = Property::find(1);
$landlordsOfProperty = $property->landlords;
$tenantsOfProperty = $property->tenants;

$tenant = Tenant::find(1);
$propertiesOfTenant = $tenant->properties;
$landlordOfTenant = $tenant->properties()
                           // ->wherePivot('property_id', 1) If searching for a particular property of tenant
                           ->last()
                           ->landlords
                           ->last();

希望这能回答您的问题.

Hope this answers your question.