与额外列的雄辩关系

时间:2015-01-23 09:19:46

标签: php laravel laravel-4 eloquent laravel-5

我有以下数据库结构:

表格地址:

id  
state -> state code
country -> country code

(上表结构无法更改)

表国家:

id
code (unique)

表陈述:

id
country_id (id from countries table)
code (unique for country_id)

问题是 - 是否可以为状态定义Address模型关系?

如果我使用:

public function stateRel()
{
    return $this->belongsTo(__NAMESPACE__ . '\\State', 'state','code');
}
它显然不会起作用,因为如果我有2个具有相同代码的州(属于其他国家/地区),它将无法找到正确的代码。它还应该使用country中的addresses来与状态中的country_id进行比较,但要使其更复杂country不会保留ID,而是来自countries的代码} table。

1 个答案:

答案 0 :(得分:1)

您是否尝试过对belongsTo关系的约束?

public function stateRel()
{
    return $this->belongsTo(__NAMESPACE__ . '\\State', 'state','code')->where('country_id', $this->country);
}
相关问题