如何通过中间国家/地区表执行某种belongsToThrough
来获取计划的货币?
这是我的数据库结构:
plan
id - integer
country_id - string // country.code
country
code - string
currency_id - string // currency.code
currency
code - string
我需要在计划模型中建立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
);
}
答案 0 :(得分:2)
您需要两个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;
答案 1 :(得分:0)
就我而言,我有
ShopOwner ->(必须)商店->(必须)员工
现在,我想获取Employees
中的所有ShopOwner
。这表示由ShopOwner过滤的员工列表。
我的员工模型:
<?php
namespace Modules\ShopOwner\Entities;
use Illuminate\Database\Eloquent\Model;
class Employees extends Model
{
public function shop()
{
return $this->belongsTo('\Modules\ShopOwner\Entities\Shops', 'shop_id');
}
public function scopeByShopowner($query, $shopownerId)
{
return $query->whereHas('shop', function ($query_shop) use ($shopownerId) {
$query_shop->where('shopowner_id', $shopownerId);
});
}
}
所以现在我可以使用:
Modules\ShopOwner\EntitiesEmployees::byShopowner($shopownerId)->get();