Laravel 5和EAV的关系
Laravel 5 and EAV relationship
我遇到了 eav 模型的问题。基本上;我有三张桌子。用户、用户信息、国家。
User userinfo Country
--------- ------------ ------------
id id id
username user_id country_name
pass option_id
etc option_value
我成功连接了用户和用户信息模型。没有问题。
我用这个检索用户模型中的用户信息:
$this->info->where('option_id', $key)->first()->option_value;
我的问题就在那里。我将 "country_id" 存储在 option_id 和 option_value 中。
例如:
userinfo
--------
id 1
user_id 5
option_id country_id
option_value 3
我是运行这个来自用户模型的查询
$this->info->where('option_id', 'country_id')->first()->option_value;
它returns 3.有没有问题。我的问题是我无法获得 country_name。
我不知道为此使用哪种关系。
我可以使用 "DB" class 进行此操作,但随后我需要对所有这些类型使用另一个查询。这不是最好的解决方案。
有人可以帮助我吗?
编辑:我正在寻找这样的解决方案(如果可能的话):
$this->info->where('option_id', $key)->first()->option_value->country_name;
编辑:我正在使用 laravel 5.1
国家模型属于用户信息。
在您的 userinfo 模型上,您应该定义关系。
用户信息Class
public function country()
{
return $this->belongsTo('App\Country', 'local_key', 'parent_key');
}
在这种情况下,您的 'local_key'
将是 'option_id'
,您的 'parent_key'
将是 'id'
。
定义关系后,您可以像这样获取国家/地区的所有属性:
$this->info->where('option_id', $key)->first()->country()->get();
我遇到了 eav 模型的问题。基本上;我有三张桌子。用户、用户信息、国家。
User userinfo Country
--------- ------------ ------------
id id id
username user_id country_name
pass option_id
etc option_value
我成功连接了用户和用户信息模型。没有问题。 我用这个检索用户模型中的用户信息:
$this->info->where('option_id', $key)->first()->option_value;
我的问题就在那里。我将 "country_id" 存储在 option_id 和 option_value 中。
例如:
userinfo
--------
id 1
user_id 5
option_id country_id
option_value 3
我是运行这个来自用户模型的查询
$this->info->where('option_id', 'country_id')->first()->option_value;
它returns 3.有没有问题。我的问题是我无法获得 country_name。 我不知道为此使用哪种关系。 我可以使用 "DB" class 进行此操作,但随后我需要对所有这些类型使用另一个查询。这不是最好的解决方案。
有人可以帮助我吗?
编辑:我正在寻找这样的解决方案(如果可能的话):
$this->info->where('option_id', $key)->first()->option_value->country_name;
编辑:我正在使用 laravel 5.1
国家模型属于用户信息。 在您的 userinfo 模型上,您应该定义关系。
用户信息Class
public function country()
{
return $this->belongsTo('App\Country', 'local_key', 'parent_key');
}
在这种情况下,您的 'local_key'
将是 'option_id'
,您的 'parent_key'
将是 'id'
。
定义关系后,您可以像这样获取国家/地区的所有属性:
$this->info->where('option_id', $key)->first()->country()->get();