mik*_*yuk 1 php laravel eloquent
我如何belongsToThrough通过中间国家表获得计划的货币?
这是我的数据库结构:
plan
id - integer
country_id - string // country.code
country
code - string
currency_id - string // currency.code
currency
code - string
Run Code Online (Sandbox Code Playgroud)
我需要currency()计划模型中的关系:
我试了几次都没有用。我想过这样的事情,但这只是返回空值:
class Plan extends \Illuminate\Database\Eloquent\Model
{
public function currency()
{
return $this->belongsTo(
Currency::class, // $related,
'currency_id', // $foreignKey = null,
'code', // $ownerKey = null,
'country' // $relation = null
);
}
Run Code Online (Sandbox Code Playgroud)
你需要两个BelongsTo关系:
class Plan extends \Illuminate\Database\Eloquent\Model
{
public function country()
{
return $this->belongsTo(Country::class, 'country_id', 'code');
}
}
class Country extends \Illuminate\Database\Eloquent\Model
{
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id', 'code');
}
}
$currency = $plan->country->currency;
Run Code Online (Sandbox Code Playgroud)
如果您想一步获得货币:
class Plan extends \Illuminate\Database\Eloquent\Model
{
public function getCurrencyAttribute()
{
return $this->country->currency;
}
}
$currency = $plan->currency;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2529 次 |
| 最近记录: |