gpt4 book ai didi

php - 属于through方法

转载 作者:行者123 更新时间:2023-12-05 01:17:26 26 4
gpt4 key购买 nike

我如何进行一种 belongsToThrough 以通过中间国家表获取计划的货币?

这是我的数据库结构:

plan
id - integer
country_id - string // country.code

country
code - string
currency_id - string // currency.code

currency
code - string

我需要 Plan 模型中的 currency() 关系:

我试了几次都没用。我想过这样的事情,但这只是返回null:

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
);
}

最佳答案

您需要两个 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;

如果想一步获取币种:

class Plan extends \Illuminate\Database\Eloquent\Model
{
public function getCurrencyAttribute()
{
return $this->country->currency;
}
}

$currency = $plan->currency;

关于php - 属于through方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50507285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com